首页 文章

打字稿中的变量键作为对象成员

提问于
浏览
2

我正在寻找一个对象的接口,该对象具有键映射到字符串值的字符串 . 这似乎是一件相当简单的事情,但我无法做到

错误显示here

我已经检查了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);

最后一行反映了我想要完成的任务

1 回答

  • 4

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

    console.log(x['question1']
    

相关问题