Typescript 误解 - 为什么记录中需要所有属性?

Wil*_*ins 6 types typescript

在这个简单的例子中:

type AllowedKeys = 'a' | 'b'

const someObject: Record<AllowedKeys, boolean> = {a:true, b:false}

const anotherObject:  Record<AllowedKeys, boolean> = {a:true}
Run Code Online (Sandbox Code Playgroud)

someObject有效但anotherObject无效:

类型 '{ a: true; 中缺少属性 'b' 但在“Record<AllowedKeys, boolean>”类型中是必需的。

为什么是这样?

T.J*_*der 4

因为Record基本上将联合展开为离散属性,如下所示:

\n
{\n    a: boolean;\n    b: boolean;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这在文档中显示:

\n
\n
interface CatInfo {\n  age: number;\n  breed: string;\n}\n \ntype CatName = "miffy" | "boris" | "mordred";\n \nconst cats: Record<CatName, CatInfo> = {\n  miffy: { age: 10, breed: "Persian" },\n  boris: { age: 5, breed: "Maine Coon" },\n  mordred: { age: 16, breed: "British Shorthair" },\n};\n
Run Code Online (Sandbox Code Playgroud)\n
\n

如果您愿意a并且b是可选的,您可以申请Partial

\n
type AllowedKeys = \'a\' | \'b\'\n\nconst someObject: Partial<Record<AllowedKeys, boolean>> = {a:true, b:false}\n//                ^^^^^^^^\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^\nconst anotherObject:  Partial<Record<AllowedKeys, boolean>> = {a:true}\n//                    ^^^^^^^^\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^\n
Run Code Online (Sandbox Code Playgroud)\n

现在,两者都有效。

\n

游乐场链接

\n