Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Special Types: never, void, unknown, any

TypeScript Special Types: never, void, unknown, any

TypeScript has four special types: never, void, unknown, and any.

They play important roles in the type system, and understanding their differences is crucial for writing type-safe code.


Comparison of the four special types any any type Bypass type checking No safety unknown Safe arbitrary type Requires checking before use Has safety void no return value Used in functions Can return undefined never Never returns Throws an exception / loops Subtype of all types Type safety level any (lowest) Completely bypasses type checking unknown Must be used after type checking void Function has no return value never (highest) Strictest and safest

Why special types are needed

TypeScript's type system is very powerful; besides regular types, it provides four special types to handle specific scenarios.

Understanding the differences among these four special types helps us write safer and more accurate typed code.

Concept explanation:never, void, unknown, and any are special types in TypeScript, each with its own meaning and use cases.


The never type

never represents a type that never returns. It is typically used for functions that throw exceptions or loop infinitely.

Example

// A function that throws an exception

// The function never returns normally; it always throws an error

function

throwError

(

message

:

string

)

:

never

{

   

throw

new

Error

(

message

)

;

}

// A function with an infinite loop

// The function never returns; the program keeps running

function

infiniteLoop

(

)

:

never

{

    while

(

true

)

{

        console.

log

(

"Running..."

)

;

   

}

}

// never is a subtype of all types

// This means never can be assigned to any type

var

neverValue

:

never

;

var

num

:

number

=

neverValue

;

 

// Correct: never is a subtype of number

console.

log

(

"Assign never to number: "

num

)

;

Running result:

never 赋值给 number: undefined

Important:never is a subtype of all types, which means never can be assigned to any type, but no type can be assigned to never (except never itself).


void type

void represents having no return value and is typically used to declare functions without a return statement.

Example

// A function with no return value

// The function returns nothing after execution

function

logMessage

(

message

:

string

)

:

void

{

    console.

log

(

"Log: "

message

)

;

   

// No return statement, or return undefined

}

logMessage

(

"Hello"

)

;

// void variable (rarely used)

// Can only be assigned undefined

var

empty

:

void

=

undefined

;

console.

log

(

"void variable: "

empty

)

;

Running result:

日志: Hello

void 变量: undefined

Explanation:void is actually very similar to undefined; it is mainly used in function return type declarations to indicate that the function has no return value.


The unknown type

unknown is the type-safe version of any. When using unknown, you must perform a type check before using it.

Example

// unknown accepts any type

// This is the "safe" any

var

value

:

unknown

=

"hello"

;

value

=

42

;

value

=

true

;

// An unknown type cannot be directly assigned to other types

// If you uncomment the next line, the compiler will report an error

// var str: string = value;

// A type check is required before assignment

if

(

typeof

value

===

"string"

)

{

   

// TypeScript knows that value is a string

   

var

str

:

string

=

value

;

    console.

log

(

"String length: "

str.

length

)

;

}

Running result:

字符串长度: 5

Safety:unknown forces a type check before use, which protects type safety. When handling data from unknown sources, you should use unknown rather than any.


The any type

any completely bypasses type checking and can be assigned any type. It is the least safe type in TypeScript.

Example

// any can be any type

// Completely bypasses type checking

var

anything

:

any

=

"hello"

;

anything

=

42

;

anything

=

true

;

// any can be assigned to any type

// This breaks type safety

var

str

:

string

=

anything

;

var

num

:

number

=

anything

;

console.

log

(

"String: "

str

)

;

console.

log

(

"Number: "

num

)

;

// An object of type any can call any method

// The compiler won't report an error, but errors may occur at runtime

var

obj

:

any

=

{

}

;

obj.

foo

(

)

;

 

// No error is reported, but the foo method does not actually exist

obj.

bar

=

"value"

;

Warning:The any type completely bypasses TypeScript's type checking and should be avoided as much as possible. When you must use it, make sure the value's type is correct.


Comparing any vs unknown

Both any and unknown can accept any type, but their safety is completely different.

Feature any unknown
Accepts any type ✓ Yes ✓ Yes
Directly assignable to other types ✓ Yes ✗ No (requires checking)
Directly call methods ✓ Yes ✗ No (requires checking)
Type Safety ✗ None ✓ Yes

Note:When handling data of unknown type, prefer unknown over any, which forces type checking.


never vs void

Both never and void are used for function return types, but their meanings are completely different.

Feature never void
Meaning Never returns No return value
Used in functions Throws an exception / infinite loop Ordinary function with no return value
Assignable to other types ✓ Yes (subtype) Can only be assigned to void/any

Key difference:never means a function never returns normally (it either throws an exception or loops forever); void means the function completes normally but has no return value.


Practical application: Exhaustive Check

An important use of the never type is exhaustive checking, ensuring that all possible cases are handled.

Example

// Define a union type of shapes

type Shape

=

{

kind

:

"circle"

,

radius

:

number

}

           

|

{

kind

:

"square"

,

side

:

number

}

;

// Calculate the area of a shape

function

area

(

shape

:

Shape

)

:

number

{

   

switch

(

shape.

kind

)

{

       

case

"circle"

:

           

return

Math

.

PI

shape.

radius

**

2

;

       

case

"square"

:

           

return

shape.

side

**

2

;

       

default

:

           

// The default branch should handle all unexpected cases

           

// If a new Shape type is added but not handled, the compiler will report an error

           

var

_exhaustive

:

never

=

shape

;

           

return

_exhaustive

;

   

}

}

var

circle

=

{

kind

:

"circle"

as

const

,

radius

:

5

}

;

var

square

=

{

kind

:

"square"

as

const

,

side

:

4

}

;

console.

log

(

"Circle area: "

area

(

circle

)

.

toFixed

(

2

)

)

;

console.

log

(

"Square area: "

area

(

square

)

)

;

Running result:

圆形面积: 78.54

正方形面积: 16

Exhaustive Check:This pattern ensures that when a new type branch is added and forgotten to be handled in the switch, the compiler reports an error because the new type cannot be assigned to never.


Notes

Best practices:Type safety from high to low: never > void > unknown > any. Use safer types whenever possible.


Summary

Understanding these four special types is very important for writing high-quality TypeScript code.

Note:When writing code, prefer stricter types. Use unknown for unknown data, void for functions with no return value, and never when exhaustive checking is needed.