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

后端 未结 9 1494
滥情空心
滥情空心 2020-11-27 15:42

Trying out TypeScript for a React project and I\'m stuck on this error:

Element implicitly has an \'any\' type because expression of type \'string\' can\'t b         


        
相关标签:
9条回答
  • 2020-11-27 16:15

    This is what it worked for me. The tsconfig.json has an option noImplicitAny that it was set to true, I just simply set it to false and now I can access properties in objects using strings.

    0 讨论(0)
  • 2020-11-27 16:19

    With out typescript error

        const formData = new FormData();
        Object.keys(newCategory).map((k,i)=>{  
            var d =Object.values(newCategory)[i];
            formData.append(k,d) 
        })
    
    0 讨论(0)
  • 2020-11-27 16:22

    When using Object.keys, the following works:

    Object.keys(this)
        .forEach(key => {
          console.log(this[key as keyof MyClass]);
        });
    
    0 讨论(0)
  • 2020-11-27 16:25

    I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.

    First, define this function to use:

    const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
    

    In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T before T extends object you break the no-use-before-define rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>).

    Anyways, with those modifications you can just use it like this:

    interface User {
      name: string;
      age: number;
    }
    
    const user: User = {
      name: "John Smith",
      age: 20
    };
    
    getKeyValue(user, "name")
    

    Which, again, I find to be a bit more readable.

    0 讨论(0)
  • 2020-11-27 16:26

    When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:

    Object.entries(data).forEach(item => {
        formData.append(item[0], item[1]);
    });
    
    0 讨论(0)
  • 2020-11-27 16:26

    Thanks to Alex Mckay I had a resolve for dynamic setting a props:

      for(let prop in filter)
          (state.filter as Record<string, any>)[prop] = filter[prop];
    
    0 讨论(0)
提交回复
热议问题