skip to Main Content

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


  1. 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;
        }
    }
    
    Login or Signup to reply.
  2. You can try to set up something along the lines of:

    interface IPeople {
      name: string;
      age: number;
    }
    
    export class People {
        name!: string;
        age!: number;
    
        constructor(props: IPeople) {
            Object.assign(this, props);
        }
    }
    

    if you want to do the same thing, but slightly more type-safe, you can just de-structure the props

    export class People {
        name: string;
        age: number;
    
        constructor({ name, age }: IPeople) {
            this.name = name;
            this.age = age;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search