Home > database >  Object.keys - Element has type "any" implicitly in Typescript
Object.keys - Element has type "any" implicitly in Typescript

Time:06-03

I have a function to obtain the key having the value of the property. When replicating this function in Typescript I get the following error:

The element implicitly has type "any" because the expression of type "any" cannot be used to index the type "TestModel"

This is my function:

interface TestModel {
    test: string,
    "test 1": string,
    data: string,
    "data 1": string
  }

getKeyByValue(value: string) {

        let data: TestModel = {
            test: "test",
            "test 1": "one Test",
            data: "data",
            "data 1": "one data"
        }

        return Object.keys(data).find((key: any) => data[key] === value);
    }

UPDATE

New function:

return Object.keys(data).find((key: string) => data[key] === value);

Error:

let data: TestModel
The element implicitly has type "any" because the expression of type "string" cannot be used to index the type "TestModel".
   No index signature found with a parameter of type "string" on type "TestModel"

CodePudding user response:

There is no need to use explicit any type for key. TS is able to figure out that type of key is string. However, we know that type of key is keyof TestModel.

Object.keys always returns string[] instead of keyof T - this is by design, for safety reasons. Hence the most common way in typescript is to use type assertion in this case:

interface TestModel {
    test: string,
    "test 1": string,
    data: string,
    "data 1": string
}

class Foo  {

    getKeyByValue(value: string) {

        let data: TestModel = {
            test: "test",
            "test 1": "one Test",
            data: "data",
            "data 1": "one data"
        }

        return (
            (Object.keys(data) as Array<keyof TestModel>)
                .find((key) => data[key] === value)
        );
    }
}

You can find more information in my article

  • Related