Search code examples
javascripttypescriptoop

What should be the Type of parameter "data" for constructor of a Class in Typescript


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


Solution

  • you an use interface checkout this LINK

    and you code will be look like that

    interface PersonData {
        name: string;
        age: number;
    }
    
    export class People {
        name: string;
        age: number;
        constructor(data: PersonData) {
            this.name = data.name;
            this.age = data.age;
        }
    }