打字稿中的地图和界面的联合(Union of map and interface in typescript)

编程入门 行业动态 更新时间:2024-10-28 06:24:54
打字稿中的地图和界面的联合(Union of map and interface in typescript)

有没有办法表达一种可以拥有任何属性的类型,但是必须具有某些属性。

所以,如果一个属性没有设置,创建这个类型会引发编译时错误,但是使用一个没有预先定义的属性也不会引发错误。

interface MyInterface { id: string; } function createObject(): MyInterface { const myObject: MyInterface = { id: "abc123", someOtherProperty: "yadda yadda" }; return myObject; } const myObject = createObject(); console.log(myObject.id); console.log(myObject.someOtherProperty);

Is there a way to express a type that CAN have ANY properties, but MUST have certain properties.

So, creating the type would throw a compile time error if a property is not set, but using a property not pre-defined would also not throw an error.

interface MyInterface { id: string; } function createObject(): MyInterface { const myObject: MyInterface = { id: "abc123", someOtherProperty: "yadda yadda" }; return myObject; } const myObject = createObject(); console.log(myObject.id); console.log(myObject.someOtherProperty);

最满意答案

当我输入我的问题时,我意识到答案是交叉类型。 谢谢橡皮鸭。

type MyIdAbleType = { id: string } & { [key: string]: any }

As I was typing my question, I realized the answer was an Intersection type. Thanks rubber duckies.

type MyIdAbleType = { id: string } & { [key: string]: any }

更多推荐

本文发布于:2023-08-07 07:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:界面   地图   Union   typescript   interface

发布评论

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

>www.elefans.com

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