码:

interface Interface {
  [id: string]: Interface2;
}

interface Interface2 {
  [id: string]: string|boolean;
}

var a:Interface = {
  abc: {
    a: 'a',
    b: 'b',
    c: 'c'
  },
  cde: {
    c: 'c',
    d: 'd',
    e: true
  }
};

if (a.cde.e) {
  console.log(1);
} else {
  console.log(2);
}

if (a['cde']['e']) {
  console.log(1);
} else {
  console.log(2);
}


在底部,您可以看到两个条件。

在第一个条件下,编译器给我一个错误:
Property 'cde' does not exist on type 'Interface'.

在第二种情况下-没有错误。

为什么编译器在第一时间抱怨?
我该如何解决?

您可以在这里尝试www.typescriptlang.org/Playground

最佳答案

[id: string]: Interface2;视为Dictionary。字典保留数据,并且键也是数据的一部分。为了拥有强类型的接口并能够访问它的属性,您可以直接向接口添加属性:

interface Interface3 {
  abc: Interface2;
  cde: Interface2;
}


在所有其他情况下,您将使用动态属性,例如使用any类型:

var c: any = a;
if (c.cde.e) {
  console.log(1);
}


或使用括号表示法

a['cde']['e']

07-24 09:46
查看更多