Property does not exist on type ‘never’ – LinuxPip (2024)

Table of contents

In TypeScript, thenevertype represents a value that will never occur. It is typically used to indicate that a function will never return a value, either because it always throws an error or has an infinite loop. Thenevertype can also be used in scenarios whereexhaustive type checkingis desired.

Here’s an example of using thenevertype in a function that always throws an error:

function throwError(message: string): never { throw new Error(message);}Code language: JavaScript (javascript)

In this example, thethrowErrorfunction has areturn typeofneverbecause it will never return a value, since it always throws an error.

The error you are encountering, Property 'X' does not exist on type 'never', indicates thatTypeScriptis unable to infer the type ofXcorrectly within your code.

This error occurs because TypeScript does not define the corresponding properties on the object when performing code inspection. This error is not fatal, and there are several possible quick fixes that make it goes away.

Set object type to any

In TypeScript, setting an object to any type means that you are disabling the type checking for that particular object. The any type allows you to use any value and call any method or property on the object, without TypeScript raising type errors.

This can be useful when you’re working with a dynamically-typed library or code that you do not control, and you cannot guarantee the types of objects being used.

However, using the any type should be done cautiously, as it essentially disables TypeScript’s type safety features for that object, potentially leading to runtime errors that could have been caught at compile time.

 this.targetArray = this.options.find((item:any) => { return item.articleId == val; });Code language: JavaScript (javascript)

Obtain object properties by characters

In TypeScript, you can access object properties using eitherdot notation(e.g.,obj.property) orbracket notationwith a string (e.g.,obj['property']).

Although dot notation is generally more common and easier to read, there are cases where using bracket notation can bring in advantages.

In this case, using bracket notation is more lenient and essentially disable the strict type checking in TypeScript, which will make Property 'X' does not exist on type 'never' disappear right away.

But be cautious as this is a quick and a dirty fix, and any errors coming from this won’t show up in the logs, which certainly don’t help debugging later on.

 this.targetArray = this.options.find((item) => { return item["articleId"] == val; });Code language: JavaScript (javascript)

Enforce type assertion

Let’s look at the following example:

 this.targetArray = this.options.find((item) => { return (item as any).articleId == val; });Code language: JavaScript (javascript)

In the code snippet, (item as any).articleId is atype assertionthat tellsTypeScriptto treatitemas an object of typeany. This allows you to access thearticleIdproperty ofitemwithout TypeScript raising atype error.

However, be cautious when usingtype assertions, as they can lead toruntime errorsif the type is not correct.

Property does not exist on type ‘never’ in Angular

Let’s consider another simple Typescript code snippet:

export class CourseEnrollmentComponent { courses!: [];}Code language: TypeScript (typescript)

In the Angular template:

<div *ngFor="let course of courses" class="w-full"> {{ course.title }}</div>Code language: HTML, XML (xml)

To fix the error, update thecomponent file so that it declares the courses array as an array of any type:

export class CourseEnrollmentComponent { courses!: any[];}Code language: JavaScript (javascript)

By default, TypeScript assigns empty arrays as never[]. This refers to an array that will always remain empty.

Property does not exist on type ‘never’ in React

The Property does not exist on type 'never' error happens in React when you forget to specify a type for astate arrayor don’t type the return value of theuseRefhook. It occurs becauseTypeScriptassigns an implicit type ofnever[]to the uninitialized array, which represents an array that will always be empty.

To fix the error in yourReact application, explicitly type the state array or theref valueusing a generic component.

Example 1: Typing a state array with useState hook

In this example, we’ll create a state array to store a list of user objects.

import React, { useState } from 'react';function UsersList() { // 👇️ Type the state array as an array of user objects const [users, setUsers] = useState<{ id: number; name: string }[]>([]); // Rest of the component logic return ( <div className="UsersList"> {/* Render users here */} </div> );}export default UsersList;Code language: TypeScript (typescript)

Example 2: Typing useRef hook

In this example, we’ll create a reference to an input element using theuseRefhook.

import React, { useRef } from 'react';function InputForm() { // 👇️ Type the ref value as an HTMLInputElement const inputRef = useRef<HTMLInputElement>(null); // Rest of the component logic return ( <div className="InputForm"> <input ref={inputRef} type="text" /> </div> );}export default InputForm;Code language: TypeScript (typescript)

By explicitly typing the state array or the ref value, you can avoid the Property does not exist on type 'never' error in your React application. Make sure to use the appropriate types for your specific use case, instead of the broaderanytype.

Using useRef hook with explicit typing in React

Using refs with theuseRefhook in React.js allows you to access and interact withDOM elementsdirectly within your components. You may encounter the error when using refs with theuseRefhook.

import React, { useRef, useEffect } from 'react';function FocusInput() { const inputRef = useRef(null); // Use the useEffect hook to focus on the input element when the component mounts useEffect(() => { if (inputRef.current) { inputRef.current.focus(); } }, []); return ( <div> <h1>Focus Input Example</h1> {/* Assign the inputRef to the input element */} <input ref={inputRef} type="text" /> </div> );}export default FocusInput;Code language: TypeScript (typescript)

To fix the error, explicitly type the ref using a generic.

import React, { useRef, useEffect } from 'react';function FocusInput() { // Create a ref to store the reference to the input element const inputRef = useRef<HTMLInputElement>(null); // Use the useEffect hook to focus on the input element when the component mounts useEffect(() => { if (inputRef.current) { inputRef.current.focus(); } }, []); return ( <div> <h1>Focus Input Example</h1> {/* Assign the inputRef to the input element */} <input ref={inputRef} type="text" /> </div> );}export default FocusInput;Code language: TypeScript (typescript)

In this example, we typed the ref as anHTMLInputElementbecause it’s assigned to an input element. For otherHTML elements, use corresponding types, e.g.,HTMLDivElement,HTMLSpanElement, etc. You can hover over anyJSX elementto see its type.

You can also type the ref as an object or any other type suitable for your use case.

import {useRef} from 'react';const ComponentA = () => { const inputRef = useRef<{name: string}>(null); console.log(inputRef.current?.name.toUpperCase()); return ( <div> <h1>Focus Input Example</h1> {/* Assign the inputRef to the input element */} <input ref={inputRef} type="text" /> </div> );};Code language: JavaScript (javascript)

Explicit typingis necessary because TypeScript can’t automatically determine the type of value you will assign to the ref. Also, note the use of the optional chaining (?.) operator, as TypeScript doesn’t know whether you’ll assign a value to the ref or anHTML element, like in previous examples.

Property does not exist on type ‘never’ – LinuxPip (2024)

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Kieth Sipes

Last Updated:

Views: 5737

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.