Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Should I use a class with constructor validation or a type with a validation function in Node?

$
0
0

When dealing with validation in Node.js (TypeScript), which is the better pattern in general and why?:

  1. Class with validation in the constructor:
    Validation happens when the object is created, ensuring it's always valid.

    class DateRange {  constructor(public startDate: Date, public endDate: Date) {    if (startDate >= endDate) {      throw new Error("startDate must be before endDate");    }  }}
  2. Type with a separate validation function:
    Decouples validation from object creation but requires explicit validation.

    type DateRange = { startDate: Date; endDate: Date };function validateDateRange(range: DateRange): boolean {  return range.startDate < range.endDate;}

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>