This is a more simple example of what I'm trying to do:
export class Person{
id:Number;
name:String;
}
export class PersonForm{
// This line:
default:Person = {name: "Guy"};
// Gives the following error:
// Error:(25, 5) TS2322: Type '{ name: string; }' is not assignable to type 'Person'.
// Property 'id' is missing in type '{ name: string; }'.
// I tried <Person>{name: "Guy"} but it gives the same error.
}
Thanks to toskv comments and this question: Constructor overload in TypeScript
I've come up with what I believe is the correct way to do it:
export class PersonForm{
constructor();
constructor(
name?:string);
constructor(
name?:string,
id?:number);
constructor(
public name?:string,
public id?:number){
}
default1:Person = new PersonForm();
default2:Person = new PersonForm("Cool Name");
default3:Person = new PersonForm("Cool Name", 123 );
}
By declaring all properties optional in the constructor implementation and overloading constructor definitions you can achieve what I was trying to achieve using a class and not having to send one entire object in the constructor, avoiding to have to build the object yourself.
Still has its perks as you will need a specific order on the parameters, but it's the best I could find. Also I didn't like the fact that I have to overload it with the same paramenters the implementation has in order to use that definition, why would I need to repeat myself?
Again, in this example yes, the best solution would be to use an interface instead, but like I mentioned before, this is not the real example (where I do need a class), just a minor version of it without the code unrelated to what I am trying to achieve.