Dictionary 无法定义打字脚本字典
我试图定义一个将键映射到数字的字典。Dictionary 无法定义打字脚本字典,dictionary,typescript,Dictionary,Typescript,我试图定义一个将键映射到数字的字典。 我发现这个{[key:string]:number} var x: {[key: string]: number} = { a: 33, b: 25 } x.a = 32; // Property 'a' does not exist on type: {[key: string]: number;} x['a'] = 32; // works as expected x['b'] = '22'; // Type 'string' is
我发现这个{[key:string]:number}
var x: {[key: string]: number} = {
a: 33,
b: 25
}
x.a = 32; // Property 'a' does not exist on type: {[key: string]: number;}
x['a'] = 32; // works as expected
x['b'] = '22'; // Type 'string' is no assignable to type 'number'
但是,这个解决方案并不完整。当我尝试使用[]手镯访问属性时,它会起作用。但不是作为对象属性。
有办法吗 我认为这是不可能的。类型系统的全部目的是允许您定义所描述对象的已知结构。否则,您可以使用
any
作为类型
但您可以使用如下示例中的对象文字,这将允许您显式指定一些已知属性,如果您的字典:
let x: { PropA: number, [x: string]: number };
x = { PropA: 1, PropX: 2, PropY: 3, PropZ: 4 };
console.log(x.PropA);
console.log(x["PropX"]);
我认为这是不可能的。类型系统的全部目的是允许您定义所描述对象的已知结构。否则,您可以使用
any
作为类型
但您可以使用如下示例中的对象文字,这将允许您显式指定一些已知属性,如果您的字典:
let x: { PropA: number, [x: string]: number };
x = { PropA: 1, PropX: 2, PropY: 3, PropZ: 4 };
console.log(x.PropA);
console.log(x["PropX"]);
但是,我不能这样做:console.log(x.PropB)仅限于console.log(x['PropB'])。这不是我想要做的…但是,我将不能做:console.log(x.PropB)only console.log(x['PropB'])。这不是我想做的。。