简体   繁体   English

如何在打字稿中定义计算属性

[英]how define computed property in typescript

I want to add an object which has dynamic property name into an array but I don't know how to define the array 我想将具有动态属性名称的对象添加到数组中,但是我不知道如何定义数组

class Driver {
    public id: string;
    public name: string;
    constructor(id , name) {
        this.id = id;
        this.name = name;
    }
}

let drivers: Driver[];
let driver = new Driver("1111","tom");
drivers.push({[driver.id]:driver})

Since you don't know what the key for those objects will be beforehand, you'll want to use an index signature . 由于您事先不知道这些对象的键是什么,因此需要使用索引签名 So for your example, you would define the type like so: 因此,对于您的示例,您将这样定义类型:

let drivers: {[id: string]: Driver}[];

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

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