比方说,我想创建一个接口来描述这种类型的对象:
Let's say I want to create an interface to describe this type of objects:
let myObj= { "count": 3, "key1": "foo", "key2": "bar", "key3": "baz" };这些对象始终具有类型为number的属性计数,其余属性为字符串
Those object always have a property count of type number and the rest of the properties are strings
如果我使用这样的索引签名定义接口:
If I define my interface using index signatures like this:
interface MyObect { count: number; [key: string]: string; }我收到了编译器错误:
[ts] Property 'count' of type 'number' is not assignable to string index type 'string'.所以我必须这样定义它:
So I have to define it like this:
interface MyObect { count: number; [key: string]: any; }但是这个定义不那么准确.
But this definition is not as presise.
有没有一种方法可以强制执行额外属性的类型?
Is there a way to enforce the type of extra properties ?
推荐答案我已经使用交集类型实现了类似的目的:
I've achieved something like this by using an intersection type:
type MyObject = { count : number } & { [key : string] : string }如下所述(我正在使用TypeScript 2.3.2)使用消费对象,如下所示
This works (I am using TypeScript 2.3.2) for consuming an object, as follows
// x : MyObject const count : number = x.count; const foo : string = x.foo但如前所述,此分配仍然失败
but as pointed out, this assignment still fails
const x : MyObject = { count: 10, foo: 'bar' }所以这可能仅在某些情况下有用.
so this may be of use only in some cases.
更多推荐
Typescript接口,强制执行额外属性的类型
发布评论