Home > Software engineering >  Getting type of property of object in array
Getting type of property of object in array

Time:04-11

You can obtain the type of a property of an object in in typescript as follows:

interface Person {
    name: string;
    realEstate: {
        street: string;
        value: number;
    }[]

}
let mrName: Person['name']

Is there any way to obtain the type of street and value?

CodePudding user response:

Have you tried this way?

let streetType : Person['realEstate'][0]['street'];

let street : typeof streetType = "Hale";

console.log(street);

let valueType : Person['realEstate'][0]['value'];

let value : typeof valueType = 10000;

console.log(value);

Alternatively, we can define it like below

interface RealEstate {
    street: string;
    value: number;
}

interface Person {
    name: string;
    realEstate: RealEstate[]
}

let realEstateType : RealEstate['street'];

let realEstate : RealEstate = {street: 'Hale', value: 10000};

console.log(realEstate);
  • Related