Typescript error: TS7053 Element implicitly has an 'any' type

Below are a few solutions to solve the "TS7053 Element implicitly has an 'any' type" error when accessing properties via array-access.

Original code:

const myObj: object = {}
const prop = 'propname'
myObj[prop] = 'string'  // Error!

Note: This does not work because the index-signature is still undefined:

const myObj: {propname: any} = {}
const prop = 'propname'
myObj[prop] = 'string'  // Error!

Solution 1: Implicit define the index signature

const myObj: {[key: string]: any} = {}
const prop = 'propname'
myObj[prop] = 'string'

Solution 2: Use an interface to provide the index signature

interface IStringIndex {
    [key: string]: any
}

const myObj: IStringIndex = {}
const prop = 'propname'
myObj[prop] = 'string'

Solution 3: Use an interface and extend the <Record> utility type:

interface IStringIndex extends Record<string, any> {}

const myObj: IStringIndex = {}
const prop = 'propname'
myObj[prop] = 'string'

Solution 4: Define a type alias with the index signature

type MyObject = {
    [key: string]: any
    propname?: any
}

const myObj: MyObject = {}
const prop = 'propname'
myObj[prop] = 'string'

Solution 5: Combination of an interface to describe the index-signature and a type alias to describe valid properties:

interface IStringIndex extends Record<string, any> {}
type MyObject = IStringIndex & {
    propname?: string
}

const myObj: MyObject = {}
const prop = 'propname'
myObj[prop] = 'string'

Solution 6: Define a list of valid (string) property names:

type ValidProps = 'propname' | 'value'
interface IStringIndex extends Record<ValidProps, any> {}

const myObj: IStringIndex = {
    propname: 'my prop',
    value: 123
}
const prop = 'propname'
myObj[prop] = 'string'

Note: All properties from the ValidProps list must be present when assigning the object!


Go to the: tsconfig.json, and set the below options

"compilerOptions": {
        "noImplicitAny": false,
}

const listOfArray: Array<any> = [];
for(const Id in MyObject)
{
   listOfArray.push(dataList[Id]);//TS7053 Error here -- Fixed by doing above things
}

Facing the same error when I tried to Push the result which comes from MyObject [{Id: value 1},{Id: 2},{Id: 3}].


You have to define what kind of index type the object has. In your case it is a string based index.

const myObj: {[index: string]:any} = {}

Tags:

Typescript