typescript 元素隐式具有 'any' 类型,因为类型 '{}' 没有索引签名。[7017]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53720424/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:44:14  来源:igfitidea点击:

Element implicitly has an 'any' type because type '{}' has no index signature. [7017]

typescripttypescript-typings

提问by peter flanagan

I am using typescript and am seeing the following error

我正在使用打字稿并看到以下错误

[ts] Element implicitly has an 'any' type because type '{}' has no index signature. [7017]

[ts] 元素隐式具有 'any' 类型,因为类型 '{}' 没有索引签名。[7017]

const store = {};
setItem: jest.fn((key, value) => {
    store[key] = value.toString();
})

I can fix it by setting the store to any like so

我可以通过将商店设置为任何类似的方式来修复它

const store: any = {};

but I would like to type it, but can't figure out how to do this. Can anyone help?

但我想输入它,但无法弄清楚如何执行此操作。任何人都可以帮忙吗?

回答by rorschach

Well, what kind of type do you want it to have? If it's just a simple key-value pair then this will suffice:

那么,你想要它有什么样的类型?如果它只是一个简单的键值对,那么这就足够了:

type Dict = { [key: string]: string };

const store: Dict = {};

store['foo'] = 'bar';

Edit (June of 2019)

编辑(2019 年 6 月)

Typescript also has a built-in type called Recordwhich is meant for this use case - as long as your type is not supposed to have any predefined keys!

Typescript 也有一个内置类型Record,它是针对这个用例的——只要你的类型不应该有任何预定义的键!

const store: Record<string, string> = {};

store.foo = 'bar';