Typescript 如何在typecscript中键入对象的某些字段
是否可以只强键入对象的子集?我试着这样做:Typescript 如何在typecscript中键入对象的某些字段,typescript,Typescript,是否可以只强键入对象的子集?我试着这样做: const foo = { // many properties here which are inferred (primitives) nested: {} as {} | { bar: string } } // simulating something that might happen if (Math.random() > 0.5) { foo.nested.bar = 'bar' // Getting the fo
const foo = {
// many properties here which are inferred (primitives)
nested: {} as {} | { bar: string }
}
// simulating something that might happen
if (Math.random() > 0.5) {
foo.nested.bar = 'bar'
// Getting the following error
// Property 'bar' does not exist on type '{} | { bar: string; }'.
// Property 'bar' does not exi st on type '{}'.
}
// Getting the same error
// Property 'bar' does not exist on type '{} | { bar: string; }'.
// Property 'bar' does not exi st on type '{}'.
console.log(foo.nested.bar)
没有办法吗
提前感谢您的帮助!:) 您正在声明的联合类型
{}{bar:string}
将不允许您访问bar
。只有当操作对参与联合的所有类型有效时,Typescript才允许操作。由于{}
没有bar
键,因此无法访问{}}{bar:string}
类型变量的bar
,正如错误告诉您的那样
如果您的目标只是使用空对象初始化嵌套的,,则可以将条定义为可选:
nested:{bar?:string}
这允许您分配空对象:nested={}
您正在声明的联合类型{}{bar:string}
将不允许您访问bar
。只有当操作对参与联合的所有类型有效时,Typescript才允许操作。由于{}
没有bar
键,因此无法访问{}}{bar:string}
类型变量的bar
,正如错误告诉您的那样
如果您的目标只是使用空对象初始化嵌套的,,则可以将条定义为可选:
nested:{bar?:string}
这允许您分配空对象:nested={}
这有帮助吗?这不应该是交叉点类型而不是并集类型吗?i、 e.嵌套:{}作为{}&{bar:string}
?我对这个问题的解释是,bar
将始终出现在对象no中?这有帮助吗?这不应该是交叉点类型而不是并集类型吗?i、 e.嵌套:{}作为{}&{bar:string}
?我对这个问题的解释是,bar
将始终出现在对象no?