问题描述
我定义了一个新的字典类,但不确定如何定义Dictionary
属性。
有一个名为Switches的json文件:
{“ ShowImage”:true,“ showtext”:false,“ showButton”,true}
import * as switches from '../switches.json';
export class DictionaryClass{
Dictionary?: { [key: string]: boolean };
}
export function getDictionary() {
const dictionaryClass = new DictionaryClass();
dictionaryClass.Dictionary = { [key: string]: boolean };
for (let entry in switches) {
dictionaryClass.Dictionary[entry] = switches[entry];
}
return dictionaryClass;
}
在此示例中,我不确定如何实例化字典,这是我尝试的一种无效的方法:
const dictionaryClass = new DictionaryClass();
dictionaryClass.Dictionary = { [key: string]: boolean };
我也尝试执行以下操作,但它也不起作用
const dictionaryClass = new DictionaryClass();
dictionaryClass.Dictionary = switches;
有人可以向我指出如何正确实例化它吗?而且,不是循环json字典,还是有将整个json字典附加到此dictionary
对象上吗?
解决方法
老实说,这里没有使用class
的意义,因为您的课程没有做任何事情。
您想要的是type
,它定义了字典的形状,这就是您在这里所拥有的:
type BooleanDictionary = { [key: string]: boolean }
所有这些其他东西都是完全不需要的,因为您的JSON已经可以自己适合该类型!这是使代码依赖类型和接口而不是特定类的优势。