我正在尝试创建递归类型( Foo )对于具有未知字段的嵌套对象:
Foo
interface Foo { [key: string]: number | Foo; } const foo: Foo = { a: 1, b: { c: 2, d: { e: 3, f: 3 // etc... } } }; const bar = foo.b.d;
上面的代码在最后一行出现错误:
Property 'd' does not exist on type 'number | Foo'. Property 'd' does not exist on type 'number'.ts(2339)
类型 foo.b number | Foo . 此处的Typescript阻止您尝试访问字段 d (或任何字段)在 number .
foo.b
number | Foo
d
number
食物b 实际上是 Foo 而不是 或者更改对象的类型。
食物b
如果你确定这是 然后 const bar = (foo.b as Foo).d typeof 检查以确保 != number .
const bar = (foo.b as Foo).d
typeof
!= number