An interface can only extend an object type or intersection of object types

avatar

Borislav Hadzhiev

Thu Mar 24 20222 min read

banner

Photo by Clay Banks

An interface can only extend an object type or intersection of object types #

The error "An interface can only extend an object type or intersection of object types with statically known members" occurs when we try to extend a non-object or non-static type in an interface. To solve the error, use a type alias with an intersection type.

interface can only extend object type

Here is an example of how the error occurs.

index.ts
type CountryOrSalary = { country: string } | { salary: number }; // ⛔️ An interface can only extend an object type or // intersection of object types with statically known members.ts(2312) interface Employee extends CountryOrSalary { id: number; name: string; }

The issue in the code snippet above is that we're trying to extend a union type using an interface.

We are only able to extend object types or an intersection of object types with statically known members, and union types are not statically known.

To solve the error in this example, use a type alias with an intersection type instead.

index.ts
type CountryOrSalary = { country: string } | { salary: number }; type Emp = CountryOrSalary & { id: number; name: string; }; const emp: Emp = { id: 1, name: 'Alice', country: 'Germany', salary: 100, };

We used a type alias and an intersection type.

Intersection types are defined using the & operator and are used to combine existing object types.

index.ts
type A = { a: string; }; type B = { b: string; }; // type Combined = { // a: string; // b: string; // } type Combined = A & B; const combined: Combined = { a: 'hello', b: 'world', };

Intersection types allow us to build up new types by extending them and are most commonly used to combine existing object types.

Alternatively, we can change the first example ot use an intersection type instead of a union:

index.ts
type CountryAndSalary = { country: string } & { salary: number }; interface Employee extends CountryAndSalary { id: number; name: string; } const emp: Employee = { id: 1, name: 'Alice', country: 'Germany', salary: 100, };

The CountryAndSalary type intersects 2 object types to produce a new type that has all of the members of both object types.

This doesn't have the same meaning as the first example which used a union type, because the country and salary properties are both required.

However, it does illustrate how changing the union type to an intersection type solves the error.

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