Property does not exist on type 'never' in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Property does not exist on type 'never' in TypeScript #

The error "Property does not exist on type 'never'" occurs when we try to access a property on a value of type never or when TypeScript gets confused when analyzing our code. To solve the error, use square brackets to access the property, e.g. employee['salary'].

Here is an example of how the error occurs.

index.ts
type Employee = { salary: number; }; let employee: Employee | null = null; function setEmployee() { employee = { salary: 100 }; } setEmployee(); // 👉️ employee.salary is equal to 100 here // but TypeScript doesn't know if (employee == null) { console.log('employee is nullish'); } else { // ⛔️ Error: Property 'salary' does not // exist on type 'never'.ts(2339) console.log(employee.salary); }

The cause of the error is that TypeScript gets confused when analyzing our code.

To solve the error, use square brackets instead of dot notation to access the property.

index.ts
type Employee = { salary: number; }; let employee: Employee | null = null; function setEmployee() { employee = { salary: 100 }; } setEmployee(); // 👉️ employee.salary is equal to 100 here // but TypeScript doesn't know if (employee == null) { console.log('employee is nullish'); } else { // ✅ Works fine now (Use bracket notation) console.log(employee['salary']); }

We used bracket notation instead of dot notation, which solved the error.

In short, do obj['myProperty'], instead of obj.myProperty.

Another cause of the error is declaring an empty array without assigning a type to it.

index.ts
const obj = { years: [], }; // 👇️ never[] console.log(obj.years);

If you declare an empty array, make sure to type it explicitly to avoid any confusing errors.

index.ts
type Example = { years: number[]; }; const obj: Example = { years: [], }; // ✅ number[] console.log(obj.years);

The three most common sources of the never type in TypeScript are:

  • having a conditional block that is never going to run, because it is impossible for the condition to be met
  • the return type of a function that throws an error
  • TypeScript getting confused when analyzing our code

Conclusion #

The error "Property does not exist on type 'never'" occurs when we try to access a property on a value of type never or when TypeScript gets confused when analyzing our code. To solve the error, use square brackets to access the property, e.g. employee['salary'].

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.