This is my code:
export class People {
name: string;
age: number;
constructor(data: any) {
this.name = data.name;
this.age = data.age;
}
}
I keep getting error for using any. What should be the type of data
so that I won’t get any error?
I know I can also do:
export class People {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
But I want this model to be used by any JSON say suppose a JSON fetched from server so that I can do:
const data = await fetchData();
const person = new Person(data)
What changes should I do to keep using the model for any object and also remove all the typescript errors?
I tried changing the type to : object
, but then I get error on data.name
and data.age
2
Answers
you an use interface checkout this LINK
and you code will be look like that
You can try to set up something along the lines of:
if you want to do the same thing, but slightly more type-safe, you can just de-structure the props