热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用打字稿的字符串索引接口?-howtousestringindexedinterfaceoftypescript?

Idliketousestringindexofinterface.我想用接口的字符串索引。interfaceIDictionary{[index:string

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.

我想这可能像映射,比如一对键和值。我不确定这是正确的方法。

1 个解决方案

#1


11  

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被推断为字符串类型:

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:

另一方面,下面是一个错误,因为它不会键入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

推荐阅读
author-avatar
coolbreeze
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有