我必须创建一个类型,它有一个必需的属性,其余的可以是任何东西。例如,我希望拥有所有具有_id: string的对象
{_id: "123"} // will work
{a: 1} // wont work because doesnt have _id field
{_id:"sadad", a:1} // will work我怎样才能用打字本做这件事?
发布于 2021-05-07 05:56:55
显式通知类型有一个带有_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 workP.S. RecordKey参考资料
https://stackoverflow.com/questions/67429586
复制相似问题