0

我必须创建一个具有一个必需属性的类型,其余的可以是任何东西。例如,我想要所有具有 _id: 字符串的对象

{_id: "123"} // will work
{a: 1} // wont work because doesnt have _id field 
{_id:"sadad", a:1} // will work

我怎么能用打字稿来做呢?

4

1 回答 1

2

显式通知类型有一个键,_id然后它可以是任何对象键值对Record<string, unknown>

type ObjectType = { _id: string } & Record<string, unknown>;

const a: ObjectType = { _id: "123" }; // will work
const b: ObjectType = { a: 1 }; // Property '_id' is missing in type
const c: ObjectType = { _id: "sadad", a: 1 }; // will work

RecordKey 的 PS 参考

打字稿中的记录类型是什么?

于 2021-05-07T05:56:55.580 回答