Typescript接口,强制执行额外属性的类型

编程入门 行业动态 更新时间:2024-10-26 07:28:08
本文介绍了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接口,强制执行额外属性的类型

本文发布于:2023-06-12 05:15:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/652004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:强制执行   属性   接口   类型   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!