Last updated: Feb 29, 2024
Reading time·2 min
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.
Here is an example of how the error occurs.
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 is that we're trying to extend a union type using an interface.
To solve the error, use a type alias with an intersection type instead.
type CountryOrSalary = { country: string } | { salary: number }; type Emp = CountryOrSalary & { id: number; name: string; }; const emp: Emp = { id: 1, name: 'Bobby Hadz', 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.
type A = { a: string; }; type B = { b: string; }; // type Combined = { // a: string; // b: string; // } type Combined = A & B; const combined: Combined = { a: 'bobby', b: 'hadz', };
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 to use an intersection type instead of a union.
type CountryAndSalary = { country: string } & { salary: number }; interface Employee extends CountryAndSalary { id: number; name: string; } const emp: Employee = { id: 1, name: 'Bobby Hadz', 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.
country
and salary
properties are both required.However, it does illustrate how changing the union type to an intersection type solves the error.
I've also written an article on how to check if an object implements an interface.
If you need to create an object based on an interface, click on the following link.