简体   繁体   English

动态填充类型 object Typescript

[英]Type for a dynamic filling object Typescript

I'm new to TypeScript and I want to try dynamic typing on one of my projects.我是 TypeScript 的新手,我想在我的一个项目上尝试动态输入。

I have an object that is initially empty but by the time it will get a structure like this:我有一个 object 最初是空的,但到时候它会得到这样的结构:

{
 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 :您可以在很大程度上按照您所说的那样定义该接口,但如果动态键始终是数字,您可以使用number

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

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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