TypeScript 中关联对象数组的接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38213926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:37:34  来源:igfitidea点击:

Interface for associative object array in TypeScript

typescripttuplesassociative-arrayunions

提问by prmph

I have an object like so:

我有一个像这样的对象:

var obj = {
    key1: "apple",
    key2: true,
    key3: 123,
    .
    .
    .
    key{n}: ...
}

So objcan contain any number of named keys, but the values must all be either string, bool, or number.

Soobj可以包含任意数量的命名键,但值必须都是字符串、布尔值或数字。

How do I declare the type of objas an interface in TypeScript? Can I declare an associative array (or variadic tuple) of a union type or something similar?

如何obj在 TypeScript中将类型声明为接口?我可以声明联合类型或类似类型的关联数组(或可变参数元组)吗?

回答by David Sherret

Yes, you can use an index signature:

是的,您可以使用索引签名

interface MyType {
    [key: string]: string | boolean | number;
}

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};