typescript - typescript 中的变量键作为对象成员

标签 typescript

我想为一个对象创建一个接口(interface),该对象具有用于将键映射到字符串值的字符串。这似乎是一件相当简单的事情,但我没能做到

显示错误 here

我已经 checkout Is it possible to define an object containing objects?Enforcing the type of the indexed members of a Typescript object?但我无法正确访问这些值。

这是代码

interface ISomeQuestions { 
    [key:string] : string; 
 }
 var x:ISomeQuestions = {
    "question1": "",
    "question2": "",
    "a": ""
};

console.log(x.question1);

最后一行反射(reflect)了我正在努力完成的事情

最佳答案

这是设计使然。因为它只有您需要使用的索引签名。

console.log(x['question1']

关于typescript - typescript 中的变量键作为对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25393288/

相关文章:

javascript - 如何在 Angular 5 中从 Typescript 调用 JavaScript 函数?

javascript - 使用 TypeScript 和采用选项对象的构造函数进行 DRY

node.js - 尝试使用 Typescript 生成 Express 的生产版本

node.js - LernaJS typescript 找不到模块

angular - 如何使用 rollup 和 terser 获取原始 TypeScript 代码的源映射?

javascript - 如何使用 TypeScript 将单独文件中的两个类合并到一个 ES6 模块中?

javascript - 智能 : Live Template to replace callback function with an es6 array function

reactjs - 如何在 TypeScript 中使用 React BluePrint 组件?

javascript - 如何从对象初始化关联数组?

node.js - 如何使用 Date.now() 修复日期错误