Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何在typecscript中键入对象的某些字段_Typescript - Fatal编程技术网

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?