Typescript对象语法问题(没有索引签名)
我正在转换一些遗留代码,如下所示:Typescript对象语法问题(没有索引签名),typescript,Typescript,我正在转换一些遗留代码,如下所示: var storage = { _cache:{}, setCache:function(key, value){ storage._cache[key] = value; } } 在Typescript中,存储。_cache[key]=值;抛出一个错误: TS7017: Element implicitly has an 'any' type because type '{}' has no index signature. 复制上述
var storage = {
_cache:{},
setCache:function(key, value){
storage._cache[key] = value;
}
}
在Typescript中,存储。_cache[key]=值;抛出一个错误:
TS7017: Element implicitly has an 'any' type because type '{}' has no index signature.
复制上述示例的各种语法是什么
在不为整个对象创建巨大接口的情况下,我唯一能弄明白的方法是首先在对象外部创建索引签名的对象:
let aMap:{ [code:string] : any } = {};
let storage = {
_cache:map
}
但我更愿意做这件事。我正在寻找更像:
let storage = {
_cache: { [code:string] : any } : {}, <-- this dont work obviously
setCache:function...
}
对于整个对象,您实际上不需要一个庞大的接口,只需执行以下操作:
interface IStorage {
[code: string]: any;
setCache: (key: string, value: any) => void;
}
let storage: IStorage = {
_cache: {},
setCache:function(key, value){
storage._cache[key] = value;
}
}
最好键入整个对象,这样可以使代码更清晰,更容易推理
或者,如果您确实想将其内联,则可以执行以下操作:
let storage: { [code: string]: any} = {
_cache: {},
setCache:function(key, value){
storage._cache[key] = value;
}
}
谢谢,你的内联示例帮助了我。const$qPredicates:{[key:string]:string}={=:==,!=:!=,>:=gt=,>=:=ge=,