Property does not exist on type 'never' in TypeScript | bobbyhadz (2024)

# Table of Contents

  1. Property does not exist on type 'never' in TypeScript
  2. Property does not exist on type 'never' in React

If you got the error in React.js, click on the second subheading.

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

The error "Property does not exist on type 'never'" occurs when we try toaccess a property on a value of type never or when TypeScript gets confusedwhen 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

Copied!

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 knowif (employee == null) { console.log('employee is nullish');} else { // ⛔️ Error: Property 'salary' does not // exist on type 'never'.ts(2339) console.log(employee.salary);}

Property does not exist on type 'never' in TypeScript | bobbyhadz (1)

If you get the error when using React.js, click on the link to scroll to thesubheading:

  • Property does not exist on type 'never' in React

The cause of the error is thatTypeScript gets confusedwhen analyzing our code.

# Use square brackets instead of dot notation to access the property

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

index.ts

Copied!

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 knowif (employee == null) { console.log('employee is nullish');} else { // ✅ Works fine now (Use bracket notation) console.log(employee['salary']);}

Property does not exist on type 'never' in TypeScript | bobbyhadz (2)

The code for this article is available on GitHub

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

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

# Using a type assertion to solve the error

You can also use a type assertion to get around the error.

index.ts

Copied!

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 knowif (employee == null) { console.log('employee is nullish');} else { // ✅ using a type assertion console.log((employee as Employee).salary);}

Property does not exist on type 'never' in TypeScript | bobbyhadz (3)

The code for this article is available on GitHub

Type assertions are used when we have information about the type of a value thatTypeScript can't know about.

We used a type assertion to set the type of the employee variable toEmployee so we can access the salary property in the else block.

If you want to turn off type checking to be able to access any property, use theany type.

index.ts

Copied!

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 knowif (employee == null) { console.log('employee is nullish');} else { console.log((employee as any).salary);}

Property does not exist on type 'never' in TypeScript | bobbyhadz (4)

The type assertion in the example sets the employee variable to have a type ofany.

The any type effectively turns off type checking, so you are able to accessany property on the variable without getting a type-checking error.

You can also use a comment to disabletype checking.

# Don't declare empty arrays without typing them

Another cause of the error is declaring anempty array without assigning atype to it.

index.ts

Copied!

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

The code for this article is available on GitHub

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

index.ts

Copied!

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

The three most common sources of thenever type in TypeScript are:

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

Want to learn more about typing arrays in TypeScript? Check out these resources: How to add Elements to an Array in TypeScript,Define an Array with Multiple types in TypeScript.

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

The error "Property does not exist on type 'never'" occurs when we forget totype a state array or don't type the return value of the useRef hook.

To solve the error, use a generic to explicitly type the state array or theref value in your React application.

Property does not exist on type 'never' in TypeScript | bobbyhadz (5)

If you got the error when declaring an array state variable with theuseState hook, use a generic totype the array.

App.tsx

Copied!

import {useState} from 'react';function App() { // 👇️ use generic to type the state array const [arr, setArr] = useState<any[]>([]); return ( <div className="App"> <div>Hello world</div> </div> );}export default App;

The example uses the very broad any type, but the concept applies to morespecific types.

# Typing a State array in React

Here are some examples of how you would use more specific types whentyping an array state variable.

App.tsx

Copied!

import {useState} from 'react';function App() { // 👇️ type it as string[] const [strArr, setStrArr] = useState<string[]>([]); // 👇️ type it as object array const [objArr, setObjArr] = useState<{name: string; age: number}[]>([]); return ( <div className="App"> <div>Hello world</div> </div> );}export default App;

If you don't explicitly type the array, it implicitly gets a type of never[],which is effectively an array that will always be empty.

I've also written a detailed guide onhow to type useState as an array or object.

# Explicitly typing the useRef hook in React.js

You might also get the error when using refs with theuseRef hook.

App.tsx

Copied!

import {useEffect, useRef} from 'react';const ComponentA = () => { const inputRef = useRef(null); useEffect(() => { // ⛔️ Error: Property 'focus' does not exist on type 'never'.ts(2339) inputRef.current?.focus(); }, []); return ( <div> <input ref={inputRef} /> </div> );};

To solve the error, use a generic to explicitly type the ref.

App.tsx

Copied!

import {useEffect, useRef} from 'react';const ComponentA = () => { // 👇️ type the ref as HTML input element const inputRef = useRef<HTMLInputElement>(null); useEffect(() => { // ✅ Works now inputRef.current?.focus(); }, []); return ( <div> <input ref={inputRef} /> </div> );};

We used a generic to type the ref as an HTMLInputElement because we areassigning the ref to an input element in the example.

Your type is likely going to be different. If it's a different HTML element,their names are consistent, e.g. HTMLDivElement, HTMLSpanElement, etc.

You can also hover over any JSX element and read its type.

If you get the error useRef "Object is possibly null", check outthe following article.

The type of the ref could be an object or whatever suits your use case.

App.tsx

Copied!

import {useRef} from 'react';const ComponentA = () => { const inputRef = useRef<{name: string}>(null); console.log(inputRef.current?.name.toUpperCase()); return ( <div> Hello World </div> );};

This is necessary because if we don't type the ref, TypeScript can't know whattype of value we will eventually assign to it.

Notice that we're also using theoptional chaining (?.) operator.TypeScript doesn't know if we're going to assign a value to the ref, or if weare going to assign it to an HTML element like in the previous examples.

If you get the "Property does not exist on type 'never'" error, chances are youforgot to explicitly type a value and it implicitly got assigned a never type.

To debug this, hover over the value and look for ways to type it - most likelywith generics if using React hooks.

# Additional Resources

You can learn more about the related topics by checking out the followingtutorials:

  • Argument of type not assignable to parameter type 'never'
  • Disable type checking for a File or a Line in TypeScript
  • How to push an Element into a state Array in React
  • Remove an Element from state Array in React
  • Property does not exist on type '{}' in TypeScript [Solved]
Property does not exist on type 'never' in TypeScript | bobbyhadz (2024)

FAQs

Property does not exist on type 'never' in TypeScript | bobbyhadz? ›

The 'does not exist on type never' error in TypeScript occurs when you try to access a property or call a method on a value with the 'never' type. Since the 'never' type represents a type that never occurs, it has no properties or methods. In the above example, the function 'throwError' has a return type of 'never'.

What is the never type in TypeScript? ›

The never type in TypeScript is a special type that represents values that can never be reached. This type is typically used to represent errors or exceptions.

How do I exclude a property from a type in TypeScript? ›

The Omit utility type is used to create a new type by excluding the specified property from the original type. Example: Here, 'type ExcludedType = Omit<FullType, 'prop2′>' ; : This defines a type ExcludedType by omitting 'prop2' from FullType.

How to access property of type in TypeScript? ›

Indexed Access Types provide a way to access the properties of an object using an index signature. In TypeScript, an index signature is a way to define the shape of an object with keys that are not known at compile time. ObjectType is the object that we want to access the properties of.

How to check if property is of type TypeScript? ›

How to Check the Type of an Object in Typescript ?
  1. Using the typeof Operator.
  2. Using the instanceof Operator.
  3. Using Type Guards.
  4. Using User-Defined Type Predicates.
Aug 1, 2024

How to check if type is never? ›

Explicit Annotation of the never Type

This kind of function must have an unreachable endpoint, for instance, an infinite loop, as shown below. In either of the case above, if you returned either of the above functions or assigned them to a variable, the inferred type is going to be never.

What is the difference between never and void in TypeScript? ›

To summarize, the never and void types in TypeScript have their own unique purposes. Void is used to indicate functions that perform actions without producing meaningful return values, while never represents values that should never occur.

What is omit properties of type in TypeScript? ›

The Omit type is a valuable utility type in TypeScript that allows you to create a new type by excluding specific properties from an existing type. It simplifies the process of defining new types based on existing ones, leaving out certain properties as needed.

How do you make a type property optional in TypeScript? ›

In TypeScript, you can make properties optional in an interface by using the question mark (?) symbol after the property name. Note: This syntax is applicable for all the examples given below, with the “?” specifying that the property is optional.

How do you ignore a type in TypeScript? ›

The // @ts-ignore comment is used in TypeScript to suppress type checking errors on the next line of code. It's often used when you're certain the code is correct but TypeScript's static type checking disagrees. In the above example, myVariable is declared as a string, but then assigned a number.

How do you declare a property in TypeScript? ›

Overview of TypeScript Property

The properties can be accessed using the 'this' keyword, so we can first define the keyword such as 'public' or 'private,' and the property can be spread over every variable declaration, function, and constructor type exported for a function declaration.

How do I check if an object has a specific property in TypeScript? ›

Ways to check the type of objects and variables
  1. The in operator. The in operator provides a way to determine if an object has a specific property with a given name. ...
  2. The instanceof operator. ...
  3. The typeof operator.

How do I make a property private in TypeScript? ›

Private accessibility is a feature of TypeScript. It marks a class property or method so that it is only accessible from within the class. The property or method is not available from any other component or service. To use private accessibility, we add the private keyword in front of the variable name.

How to check if element is of type in TypeScript? ›

In Typescript, we have three ways to work with it using:
  1. typeof: the keyword helps to check values types, like boolean, string, number, etc.
  2. instanceof: the keyword to compare the object instance with a class constructor.
  3. type guards: The powerful way to check types using typescript feature language.
Aug 10, 2022

How to check if key exists on type in TypeScript? ›

Using an 'in' operator

The 'in' operator checks whether a specific key or a property exists in an object or not. It is a widely used approach as it provides a simplistic way to check the existence of a key in TypeScript dictionaries.

How to check if object property is not undefined in TypeScript? ›

Using the “!” Operator

The “!” operator is called the non-null assertion operator. It tells TypeScript that a variable or property is not null or undefined, even if TypeScript's type checker thinks it could be.

What is the difference between any and never in TypeScript? ›

any says give me anything, and never says give me nothing. never is used when we have exhausted all possible value and we don't have anything to assign. Let's see some cases where we don't have anything to assign. Here in else block, if we get anything other than string or number then error will be thrown.

What is a never array TypeScript? ›

In TypeScript, the empty arrays are inferred as never[] by default, denoting an array incapable of containing any elements. This occurs when TypeScript fails to deduce the type of array elements from the context, notably in scenarios involving spread operators, the Array constructor, or methods like Array.

What is the undefined type in TypeScript? ›

undefined indicates that a variable has been declared but hasn't been assigned any value. It's commonly used to represent missing function arguments or uninitialized object properties.

What is the T type in TypeScript? ›

So, instead, we define a generic ( T ), which is used to type the argument being passed in as well as the return value. This generic value will be replaced at runtime with a more accurate type which you can see when we call the function and pass in the values <number> and <string> .

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5729

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.