简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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