javascript - Typescript:为什么当使用 [id: string]: any 描述接口(interface)中的对象时出现错误?

标签 javascript typescript

代码:

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);
}

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

在第一个条件下,编译器给出一个错误: 类型“Interface”上不存在属性“cde”。

在第二个条件下 - 没有错误。

为什么编译器在第一个条件下会提示? 我该如何解决这个问题?

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

最佳答案

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

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

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

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

或使用括号表示法

a['cde']['e']

关于javascript - Typescript:为什么当使用 [id: string]: any 描述接口(interface)中的对象时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054588/

相关文章:

javascript - Nightmare.js 未处理的 promise 拒绝

javascript - Three.js OrbitControls 补间动画到目标对象的正面(前面)

javascript - D3 可缩放 y 轴(以小时为单位)

javascript - jQuery .trigger() 多个事件

arrays - typescript :数组类型取决于先前的数组元素

javascript - Angular2 - 如何从 typescript 获取变量到我的 html dom

javascript - 使用 Javascript 异步和等待 google.script.url.getLocation

angular - 在 Angular 组件之间共享字符串

typescript - 为 Typescript Record 定义可选键列表

TypeScript、Webpack、ES6 风格的模块但针对 ES5