typescript 如何使用打字稿的字符串索引接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29043279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use string indexed interface of typescript?
提问by idpokute
I'd like to use string index of interface.
我想使用接口的字符串索引。
interface IDictionary {
[index: string]: string;
}
var params: IDictionary;
params = [{ "heart": "HP" }, { "mana": "MP" }];
console.log(params);
I thought this might be like MAP such as a pair of key and value. I'm not sure this is correct approach.
我认为这可能类似于 MAP,例如一对键和值。我不确定这是正确的方法。
回答by basarat
Using the indexer limits what can be put or fetched for the object using the index syntax. E.g. foo
is inferred to be of type string
:
使用索引器限制可以使用索引语法为对象放置或获取的内容。例如foo
推断为类型string
:
interface IDictionary {
[index: string]: string;
}
var params = {} as IDictionary;
params['heart'] = 'HP'; // okay
var foo = params['heart']; // foo:string
The following on the other hand is an error as it will not type check:
另一方面,以下是错误,因为它不会进行类型检查:
var bar:number = params['heart']; // ERROR
params['heart'] = 234; // ERROR
Complete demo:
完整演示:
interface IDictionary {
[index: string]: string;
}
var params = {} as IDictionary;
params['heart'] = 'HP'; // okay
var foo = params['heart']; // foo:string
var bar:number = params['heart']; // ERROR
params['heart'] = 234; // ERROR