简体   繁体   English

如何在typescript接口中表示变量键名?

[英]How to represent a variable key name in typescript interface?

interface Items {
    id: Item,
}

id is not optional but it will have different name id不是可选的,但它将具有不同的名称

for example: 例如:

let items = {
34433ded : {name: "foo", price: 0.99},
14d433dee : {name: "bar", price: 1.99},
}

Something like: 就像是:

interface Item {
    name: string;
    price: string;
}

type Items = { [id: string]: Item }

let items = {
    34433ded : {name: "foo", price: 0.99},
    14d433dee : {name: "bar", price: 1.99},
} as Items;

You can achive this by following structure: 您可以通过以下结构实现此目的:

interface Items {
    [key: string]: Item;
}

Here is your fiddle . 这是你的小提琴
But remember due to JSON specification your object keys should't begin with numbers or if they do - you have to wrap them in quotes (as I did in fiddle) 但是请记住,由于JSON规范,你的对象键不应该以数字开头,或者如果它们这样做 - 你必须将它们用引号括起来(就像我在小提琴中所做的那样)

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

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