Issue
currently I define my model classes in this way:
export class Company {
constructor(
public id?: number,
public name?: string,
public shortName?: string
) {}
}
The reason, why I use ?
is that in this case I don't get an error that values for properties aren't provided if I want to assign an empty company
object to a variable like this:
this.editDataItem = new Company();
Can I somehow avoid the use of ?
in the model declaration? Or is this the right way if I want to assign an empty instance to a variable without declaring all the properties? Are there any best practices for this?
Solution
The ?
is just a shorthand for undefined
.
To prevent a property being undefined
you would need to set it on initialization either by passing values to the constructor or setting default values.
Depending on your use-case this is a perfectly valid and correct way to define a models property types.
You might as well change your class to:
export class Company {
id?: number;
name?: string;
shortName?: string;
constructor(
) {}
}
Now you still have public properties but they are undefined
by default and there is no need to pass any values to the constructor.
Answered By - Philipp Meissner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.