简体   繁体   中英

Type for a dynamic filling object Typescript

I'm new to TypeScript and I want to try dynamic typing on one of my projects.

I have an object that is initially empty but by the time it will get a structure like this:

{
 index: 2,
 0: {
    prop1: 4,
    prop2: 8,
    prop3: 15,
 },
 1: {
    prop1: 4,
    prop2: 8,
    prop3: 15,
 }
 // And so on
}

I tried different approaches but nothing worked well, the last thing I tried was this type:

{
    index: number;
    [key: string]: {
        prop1: number;
        prop2: number;
        prop3: number;
    }
};

It says that I can't use this type for my objects.

You can define that interface largely as you said you tried to, though if the dynamic keys are always numbers, you can use number :

interface TheThing {
    index: number;
    [key: number]: {
        prop1: number;
        prop2: number;
        prop3: number;
    }
}

Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM