prm*_*mph 23 associative-array tuples unions typescript
我有一个像这样的对象:
var obj = {
key1: "apple",
key2: true,
key3: 123,
.
.
.
key{n}: ...
}
Run Code Online (Sandbox Code Playgroud)
因此obj可以包含任意数量的命名键,但值必须都是string,bool或number.
如何obj在TypeScript中声明接口的类型?我可以声明一个联合类型或类似的关联数组(或可变参数元组)吗?
Dav*_*ret 39
是的,您可以使用索引签名:
interface MyType {
[key: string]: string | boolean | number;
}
var obj: MyType = {
key1: "apple",
key2: true,
key3: 123
};
Run Code Online (Sandbox Code Playgroud)
在阅读了这个问题和大卫的回答后,我更深入地研究了文档,并提出了一个很棒的解决方案!
我已经使用通用类型创建了一个字典接口!
interface Dictionary<Type> {
[key: string]: Type;
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样(重新)使用它:
const myNumbers:Dictionary<number> = {
key1: 1,
key2: 2,
key3: 3
};
const myStrings: Dictionary<string> = {
key1: 'Lorem',
key2: 'Ipsum',
key3: 'Dolor'
};
const myElements:Dictionary<HTMLElement> = {
button: document.querySelector('#button'),
input: document.querySelector('#input')
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10984 次 |
| 最近记录: |