Search code examples
reactjstypescripttypescript-typings

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index 'ModuleType'


I have types

type Link = {
  type: number | string;
  productIds: Array<string>;
};

export type ModuleType = {
  '@type': string;
  title: string;
  text: string;
  position: string;
  backgroundStyle: string;
  latitude: string;
  longitude: string;
  background: File;
  link: Link;
};
const formDataType = formData[link].type;

Here formData has a type ModuleType and I'm trying take object key with a string, but I have got an error in TS: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ModuleType'.   No index signature with a parameter of type 'string' was found on type 'ModuleType'. I need take link key from the object

Thanks in advance!


Solution

  • you have to tell TypeScript that the keyword name is a key of type ModuleType.

    For that you have to write like this,

    
    let name : keyof ModuleType = 'Whatever value it contains';
    
    const formDataType = formData[name].type;
    
    //  or
    
    const formDataType = formData[<keyof ModuleType>name].type;