【发布时间】:2017-11-05 14:48:44
【问题描述】:
假设我想创建一个接口来描述这种类型的对象:
let myObj= {
"count": 3,
"key1": "foo",
"key2": "bar",
"key3": "baz"
};
那些对象总是有一个 number 类型的属性计数,其余属性是字符串
如果我使用这样的索引签名定义我的界面:
interface MyObect {
count: number;
[key: string]: string;
}
我得到了编译器错误:
[ts] Property 'count' of type 'number' is not assignable to string index type 'string'.
所以我必须这样定义:
interface MyObect {
count: number;
[key: string]: any;
}
但这个定义并不像现在这样。
有没有办法强制执行额外属性的类型?
【问题讨论】:
-
你可以用
[key: string]: string | number缩小范围
标签: typescript types interface