typescript 如何键入另一条记录的keyof,但允许0或更多键

weylhg0b  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(139)

TS抱怨foo中缺少b,但我只需要其中的一些键。如何正确打字?

const shape = {a: 1, b:2}

const foo: Record<keyof typeof shape, any> = {
  a: 42,
}

// Error: Property 'b' is missing in type '{ a: number; }' but required in type 'Record<"a" | "b", any>'.
dhxwm5r4

dhxwm5r41#

您应该使用内置的实用程序类型Partial,它将对象的所有字段转换为可选:

const shape = { a: 1, b: 2 };

const foo: Partial<Record<keyof typeof shape, any>> = {
  a: 42,
}; // no error

相关问题