Property does not exist on type ‘never’ in TypeScript

Understanding the error “Property does not exist on type ‘never'”

c This error can be frustrating and confusing, but it is relatively easy to solve once we understand the cause.

Causes of the error “Property does not exist on type ‘never'”

One common cause of the error is when we try to access a property on a null or undefined value. For example, consider the following code:

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);
}

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

const obj = {
  years: [],
};

// never[]
console.log(obj.years);

Solutions Property does not exist on type ‘never’:

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

[Fixed]: AttributeError module ‘datetime’ has no attribute ‘now’

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']);
}

To avoid this error, make sure to type the empty array explicitly.

type Example = {
  years: number[];
};

const obj: Example = {
  years: [],
};

// number[]
console.log(obj.years);

Conclusion: Property does not exist on type ‘never’

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, we can use square brackets instead of dot notation to access the property or make sure to type empty arrays explicitly. Understanding the causes of this error can help us write better TypeScript code and avoid frustrating mistakes in the future.

Leave a Reply