Binding element 'X' implicitly has an 'any' type in TS

avatar

Borislav Hadzhiev

Thu Mar 17 20222 min read

Binding element 'X' implicitly has an 'any' type in TS #

The error "Binding element implicitly has an 'any' type" occurs when a function takes an object as a parameter, but we don't set the object's type. To solve the error, make sure to explicitly type the object parameter of the function.

Here is an example of how the error occurs in functions and in class methods.

index.ts
// 👇️ With Functions 👇️ // ⛔️ Error: Binding element 'id' implicitly // has an 'any' type.ts(7031) function getEmployee({ id, name }) { return { id, name }; } // 👇️ With Class methods 👇️ class Employee { id: number; name: string; // ⛔️ Error: Binding element 'name' implicitly // has an 'any' type.ts(7031) constructor({ id, name }) { this.id = id; this.name = name; } }

The problem is that the functions take an object as a parameter, we destructure the object's properties, but don't type the object.

This means that the type of the object's properties is implicitly set to any.

To solve the error, type the object by separating the object parameter and its type by a colon.

index.ts
// 👇️ With Functions 👇️ function getEmployee({ id, name }: { id: number; name: string }) { return { id, name }; } // 👇️ With class methods 👇️ class Employee { id: number; name: string; constructor({ id, name }: { id: number; name: string }) { this.id = id; this.name = name; } }

If you don't want to explicitly type the object parameter, but need to suppress the error, use the any type.

index.ts
function getEmployee({ id, name }: any) { return { id, name }; } class Employee { id: number; name: string; constructor({ id, name }: any) { this.id = id; this.name = name; } }

Note that the any type effectively turns off type checking and should be used sparingly.

When typing an object parameter in TypeScript, always make sure to separate the parameter definition and the type with a colon. For example, this is not valid syntax.

index.ts
// ⛔️ Binding element 'number' implicitly has an 'any' type. function getEmployee({ id: number, name: string }) { return { id, name }; }
What we are doing in the example is destructuring the id property and giving it a name of number.

And destructuring the name property from the object and giving it a name of string.

Instead, the types should be defined separately.

index.ts
function getEmployee({ id, name }: { id: number; name: string }) { return { id, name }; }

If your function definition gets too busy, you can extract the object type into a type alias or an interface.

index.ts
type Employee = { id: number; name: string; tasks: string[]; }; function getEmployee({ id, name, tasks }: Employee) { return { id, name, tasks }; }

This is a bit easier to read, especially when the object your function takes contains many properties.

Use the search field on my Home Page to filter through my more than 1,000 articles.