在这个简单的例子中:
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>”类型中是必需的。
为什么是这样?
因为Record基本上将联合展开为离散属性,如下所示:
{\n a: boolean;\n b: boolean;\n}\nRun Code Online (Sandbox Code Playgroud)\n这在文档中显示:
\n\n\nRun Code Online (Sandbox Code Playgroud)\ninterface 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
如果您愿意a并且b是可选的,您可以申请Partial:
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^\nRun Code Online (Sandbox Code Playgroud)\n现在,两者都有效。
\n\n| 归档时间: |
|
| 查看次数: |
552 次 |
| 最近记录: |