Typescript接口,强制执行额外属性的类型 [英] Typescript Interface, enforce the type of extra properties

查看:146
本文介绍了Typescript接口,强制执行额外属性的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我想创建一个接口来描述这种类型的对象:

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接口,强制执行额外属性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆