打字稿中的地图和界面的联合(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 }更多推荐
发布评论