Understanding the TypeScript never Type > dev

Skip to content

Entire search within the site

👈Go back dev

TypeScript Understanding the TypeScript never Type

page info

name Goposu datetime⏰ 25-10-10 17:36 hit👁️ 25 comment💬 0

text

Understanding the TypeScript never Type

Understanding the TypeScript never Type

Published on October 10, 2025

What is never in TypeScript?

The never type represents values that never occur. It is typically used to indicate that a function never returns, such as when it throws an error or enters an infinite loop.

Basic Example

function throwError(message: string): never {
  throw new Error(message);
}

In this example, the function always throws an error, so it never returns a value. TypeScript infers the return type as never.

Use Cases

  • Functions that always throw errors
  • Infinite loops
  • Exhaustive type checking in switch statements

Comparison with Other Types

Type Description
any Allows any value and disables type checking
void Represents functions that return nothing
never Represents functions that never return

Exhaustive Type Checking Example

type Shape = "circle" | "square";

function handleShape(shape: Shape) {
  switch (shape) {
    case "circle":
      // handle circle
      break;
    case "square":
      // handle square
      break;
    default:
      const exhaustiveCheck: never = shape;
      throw new Error(`Unhandled shape: ${shape}`);
  }
}

This pattern ensures that all possible cases are handled. If a new shape is added and not handled, TypeScript will show an error.

Author: Your Name

Tags: TypeScript, never, types, programming

👍good0 👎nogood 0

comment list 0

There are no registered comments.

이미지 목록

전체 19건 1 페이지
게시물 검색
Copyright © https://goposu.com All rights reserved.
View PC version