繁体   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,…}`

我创建了这个助手来返还增值税。

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;
};

但是收到此类型错误元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型...'

有任何想法吗?

您可以在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM