Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  42] [ 7]  / answers: 1 / hits: 12169  / 3 Years ago, tue, april 20, 2021, 12:00:00

I'm trying to create a TS User class with angular. I declared my attributes as shown in the code below, but I'm getting this error.



An argument for 'id' was not provided.





export class User {

private id: number;
private etabName: string;


constructor(id: number, etabName: string, ) {
this.id = id;
this.etabName = etabName;

}

get _id(): number {
return this. id;
}

set _id(value: number) {
this. id = value;
}



}




More From » angular

 Answers
4

Original Answer


The issue occurs when you try to instantiate the class without passing arguments, as you did not specify arguments will be optional.


Make arguments optional like this


export class User {
...

constructor(id?: number, etabName?: string, ) {
this.id = id || 0; //Specify default value
this.etabName = etabName || ''; //Specify default value

}
...
}

then you can instantiate class without arguments


const user = new User();//works

Update


You can write it even better with this syntax below, Typescript will take care of creating properties and assigning default values to it.


class User {
constructor(private id: number = 0, private etabName: string = '') {
}

...setters and getters omitted for readability
}

The above typescript will be converted to below javascript


class User {
constructor(id = 0, etabName = '') {
this.id = id;
this.etabName = etabName;
}
...setters and getters omitted for readability
}

[#1459] Sunday, April 11, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;