TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'

前端 未结 4 2066
故里飘歌
故里飘歌 2020-12-09 14:40

Im getting this compilation error in my Angular 2 app:

TS7015: Element implicitly has an \'any\' type because index expression is not of type \'number\'.
         


        
4条回答
  •  青春惊慌失措
    2020-12-09 15:13

    I was actually working with React and I got this error when I assigned an object's property through a custom key (i.e. myObj[myKey] = ). To resolve it, I simply used as keyof:

    interface IMyObj { title: string; content: string; }
    const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' };
    const myKey: string = 'content';
    
    myObj[myKey as keyof IMyObj] = 'All is great now!';
    

    This explicitly tells Typescript that your custom string (myKey) belongs to the group of properties from an interface/type you used for declaring your object (myObj).

    P.S.: another way to get the property's value is shown on a closed Typescript's issue on Github through extends:

    interface IMyObj {
      title: string;
      content: string;
    }
    
    const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' };
    const myKey: string = 'content';
    
    const getKeyValue = (obj: T) => (key: U) =>
      obj[key];
    console.log(getKeyValue(myObj)(myKey));

提交回复
热议问题