0

I'm reading in Todo instances from a CSV file and Papaparse does not do dynamic conversion on dates so I can drop the object into its own constructor to do the conversion:

class Todo {
    public dueDate:Date;
    ....
    constructor(todo:Todo) {
       this.dueDate = new Date(todo.dueDate);
       ...
    }
}

Is there exists a more sugared approach to initializing the properties via the constructor

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 1
    I don't believe so, but you could do something like this https://stackoverflow.com/questions/32413025/es6-destructuring-in-class-constructor – Tommy May Mar 26 '19 at 04:08
  • I tried `Object.assign` but it does not do the date conversion - Just assigns the same strings that are on the constructor object ... – Ole Mar 26 '19 at 04:18
  • Maybe I'm not fully understanding your question.. I think your asking how do you initialize values on the constructor without specifying each value, in which case `Object.assign` is what your looking for. It will not handle any additional logic you want to perform on those properties but you could do it in the assign... `Object.assign(this, todo, {dueDate: new Date(todo.dueDate)})` – Tommy May Mar 26 '19 at 04:28
  • So you are mistyping the constructor parameter? It doesn't accept a `Todo` at all, but something like `{[K in keyof Todo]: Todo[K] extends Date ? string : Todo[K]}` (meaning `{dueDate: string}` in your stripped-down example) – jcalz Mar 26 '19 at 16:15
  • @jcatz - No the constructor parameter takes a parameter that is an instance of the `Todo` class. Although it's not a valid instance, because the date is a string. So within the constructor the date string is wrapped in a new `Date` object. This way the instance can be validated using an `@IsDate` validation annotation. – Ole Mar 26 '19 at 18:53

1 Answers1

1

Use TypeScripts auto properties, constructor parameters become properties with protected, public and private prefixes.

class Todo {
    constructor(public dueDate:Date) { }
}
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • I don't think I can do that because I'm annotating the properties with validation constraints like `@IsDate dueDate`. IIUC that means we can't place the properties within the constructor? – Ole Mar 26 '19 at 04:23
  • Why would you validate with model decorators? Should validation not be a form concern? – Adrian Brand Mar 26 '19 at 04:25
  • Using this library ... that I built ... gotta eat my own dog food ... https://www.npmjs.com/package/@fireflysemantics/validator – Ole Mar 26 '19 at 04:49
  • These are CSV records being read in ... mostly business data ... like purchase orders etc. The Todo class illustration was just to keep it simple. I mainly need the date conversion, as papaparse converts numbers and booleans. – Ole Mar 26 '19 at 04:50