我有一个格式的对象
export const IconSizeMap = {
'extra-small': '0.75rem',
small: '1rem',
medium: '1.5rem',
large: '2rem',
'extra-large': '4rem'
};
作为 typescript 的新手,我无法理解错误是什么
报错
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 'extra-small': string; small: string; medium: string; large: string; 'extra-large': string; }'.
No index signature with a parameter of type 'string' was found on type '{ 'extra-small': string; small: string; medium: string; large: string; 'extra-large': string; }'.ts(7053)
当我尝试使用时
IconSizeMap[size]
我该如何解决这个错误?
最佳答案
您收到此错误是因为您的 tsconfig.json
启用了 "noImplicitAny": true
。这意味着 TypeScript 会查找并通知您在哪些地方使用了类型未知的值,以及您没有明确告诉他应该是哪种类型。
您摆脱它的解决方案是:
- 在配置中禁用
noImplicitAny
(但我想这是有原因的,所以我不建议这样做) - 告诉 TypeScript 你正在使用的导致错误的类型。
在这里,TypeScript 识别出您定义的 5 个键中的每一个(extra-small
、small
、medium
、large
和 extra-large
),因为您为它们分配了一个 string
值,因此它可以判断它们是字符串。但是,只有这 5 个 string
是键。
当您使用“通用” string
来访问您的对象时,例如我假设您的 size
是什么,您不确定它是否对应于一个的 5 个键。所以,TypeScript 会警告你。
一种解决方案可能是告诉编译器您确定自己在做什么,并更准确地指定 size
的类型。例如:
export const IconSizeMap = {
'extra-small': '0.75rem',
small: '1rem',
medium: '1.5rem',
large: '2rem',
'extra-large': '4rem'
};
let size: keyof typeof IconSizeMap; // Means "I'm sure that size is one of those strings
size = "small";
console.log(IconSizeMap[size]);
关于javascript - 在 typescript 中定义对象并访问它的值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63357074/