简体   繁体   English

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ AT: number; BE:数字,...}`

[英]Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ AT: number; BE: number,…}`

I have created this helper to return VAT.我创建了这个助手来返还增值税。

export const hasVAT = (country: string) => {
  const VATRates = {
   AT: 20, // Austria,AT
   BE: 21, // Belgium,BE
   BG: 19, // Bulgaria,BG
   CZ: 21, // Czech Republic,CZ
   CY: 19, // Cyprus,CY
   DK: 25, // Denmark,DK
   ...
 };
 return country in VATRates ? VATRates[country] : false;
};

But receiving this Type error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type...'但是收到此类型错误元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型...'

any ideas?有任何想法吗?

You can enforce typing on object keys, so your helper can be written as:您可以在 object 键上强制键入,因此您的助手可以写成:

export const hasVAT = (country: string) => {
  const VATRates: {[key: string]: number} = {
   AT: 20, // Austria,AT
   BE: 21, // Belgium,BE
   BG: 19, // Bulgaria,BG
   CZ: 21, // Czech Republic,CZ
   CY: 19, // Cyprus,CY
   DK: 25, // Denmark,DK
 };

 return country in VATRates ? VATRates[country] : false;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ A:数字; B:数字 - TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ A: number; B: number 元素隐式具有“any”类型,因为“number”类型的表达式不能用于索引类型“{}” - Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}' 元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型“{ 1: number; 2:号码; 3:号码; }' - Element implicitly has an 'any' type because the expression of type 'any' can't be used to index type '{ 1: number; 2: number; 3: number; }' Typescript 元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引 - Typescript Element implicitly has an 'any' type because expression of type 'number' can't be used to index 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“BGColors” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'BGColors' 如何修复 Element 隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型? - how fix Element implicitly has an 'any' type because expression of type 'string' can't be used to index type? 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型 React Typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type React Typescript 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '' 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}' 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型 - Phaser - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type - Phaser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM