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

TypeScript Type Assertions

TypeScript Type Assertions

Type assertion (Type Assertion) is a mechanism that tells the compiler "I know the type of this value better than you do". It allows developers to manually override TypeScript's type inference, similar to type casting in other languages, butonly takes effect at compile time and produces no runtime code.。


Two syntax forms

Type assertions have two forms; it is recommended to consistently use the as as syntax, since angle-bracket syntax conflicts with tag syntax in JSX files.

Example

// ① Angle-bracket syntax (not recommended, cannot be used in .tsx files)

const

str1

:

any

=

"hello"

;

const

len1

:

number

=

(

<

string

str1

)

.

length

;

// ② as syntax (recommended)

const

str2

:

any

=

"world"

;

const

len2

:

number

=

(

str2 as string

)

.

length

;

console.

log

(

len1

)

;

 

// 5

console.

log

(

len2

)

;

 

// 5

Running result:

5

5

Note:In React's .tsx files, the angle-bracket form conflicts with JSX tags, so the as syntax must be used. as syntax.


Common usage scenarios

1. Handling any / unknown types

Data obtained from external APIs, JSON parsing, and similar scenarios is usually of type any, anyso type hints can be restored through assertions.

Example

const

response

:

any

=

{

name

:

"Alice"

,

age

:

25

}

;

// Assert as a specific type to get type hints

const

user

=

response as

{

name

:

string

;

age

:

number

}

;

console.

log

(

user.

name

)

;

 

// Alice

console.

log

(

user.

age

)

;

 

// 25

Running result:

Alice

25

2. Narrowing union types

When a specific branch of a union type is known but the compiler cannot determine it automatically, you can use an assertion to clarify the type.

Example

type Shape

=

   

|

{

kind

:

"circle"

;

radius

:

number

}

   

|

{

kind

:

"rect"

;

width

:

number

;

height

:

number

}

;

function

getArea

(

shape

:

Shape

)

:

number

{

   

if

(

shape.

kind

===

"circle"

)

{

       

return

Math

.

PI

(

shape as

{

kind

:

"circle"

;

radius

:

number

}

)

.

radius

**

2

;

   

}

   

const

rect

=

shape as

{

kind

:

"rect"

;

width

:

number

;

height

:

number

}

;

   

return

rect.

width

rect.

height

;

}

console.

log

(

getArea

(

{

kind

:

"circle"

,

radius

:

5

}

)

.

toFixed

(

2

)

)

;

 

// 78.54

console.

log

(

getArea

(

{

kind

:

"rect"

,

width

:

4

,

height

:

6

}

)

)

;

   

// 24

Running result:

78.54

24

Tip:Prefer type guards (such as typeof or instanceoftypeof / instanceof or discriminant properties) to narrow types, and use assertions only when guards cannot cover the case.

3. Working with DOM elements

document.querySelector returns a Element | nullYou must assert to a specific element type before accessing its dedicated properties.

Example

// querySelector returns Element | null

const

input

=

document.

querySelector

(

"#username"

)

as HTMLInputElement

;

// After asserting, you can access the dedicated properties of HTMLInputElement

// console.log(input.value);

// A safer approach: check for null first, then assert

const

btn

=

document.

querySelector

(

"#submit"

)

;

if

(

btn

)

{

   

(

btn as HTMLButtonElement

)

.

disabled

=

true

;

}


Non-null assertion !

Add an exclamation mark after a value !to tell the compiler that the value is not null or undefinednull; this applies when you can guarantee non-null but the compiler cannot infer it.

Example

function

printLength

(

str

?:

string

)

{

   

// Use ! to assert that str definitely has a value

    console.

log

(

str

!

.

length

)

;

}

// Runs normally

printLength

(

"hello"

)

;

 

// 5

// Runtime error: Cannot read properties of undefined

// printLength();

Running result:

5

Warning:Non-null assertions bypass the compiler's null checks; if the actual value is null / undefinednull or undefined, a runtime error will still be thrown. When possible, prefer optional chaining. ?. instead.


Const assertions as const

as const Infers literals as the narrowest read-only literal type, commonly used to define enum values, configuration constants, and tuples.

Example

// Normal declaration: inferred as string[], elements are mutable

const

colors1

=

[

"red"

,

"green"

,

"blue"

]

;

colors1.

push

(

"yellow"

)

;

 

// Allowed

// as const: inferred as readonly ["red", "green", "blue"], elements and length are both immutable

const

colors2

=

[

"red"

,

"green"

,

"blue"

]

as

const

;

// colors2.push("yellow"); // Error: cannot push to a readonly array

// The same applies to objects: all properties become readonly literal types

const

config

=

{

    host

:

"localhost"

,

    port

:

3000

}

as

const

;

// config.port = 8080; // Error: readonly properties cannot be modified

console.

log

(

colors2

)

;

       

// ['red', 'green', 'blue']

console.

log

(

config.

host

)

;

   

// localhost

console.

log

(

config.

port

)

;

   

// 3000

Running result:

['red', 'green', 'blue']

localhost

3000


Assertions are not type conversions

Type assertions only affect the compiler's type checking; no conversion code is generated after compilation. When you assert "42" as number, it is still a string at runtime.

Example

const

strNum

:

any

=

"42"

;

// Asserted as number, but still a string at runtime

const

wrongNum

=

strNum as number

;

console.

log

(

typeof

wrongNum

)

;

   

// string (not number!)

console.

log

(

wrongNum

1

)

;

     

// 421 (string concatenation, not numeric addition)

// A real type conversion requires a conversion function

const

realNum

=

Number

(

strNum

)

;

console.

log

(

typeof

realNum

)

;

   

// number

console.

log

(

realNum

1

)

;

       

// 43

Running result:

string

421

number

43


Double assertions

When there is no overlap between two types, TypeScript refuses a direct assertion. In this case, you can use unknown as an intermediate, but this is a dangerous operation and should be avoided whenever possible.

Example

const

num

=

42

;

// Direct assertion: number and string have no overlap, the compiler reports an error

// const str = num as string;

// Double assertion: first assert as unknown, then assert as the target type

const

str

=

num as unknown as string

;

console.

log

(

str

)

;

         

// 42

console.

log

(

typeof

str

)

;

 

// number (the runtime type is unchanged; assertions only take effect at compile time)

Running result:

42

number

Warning:Double assertions completely bypass TypeScript's type system and can easily cause runtime errors. Use them only in special cases such as when third-party library types are inaccurate, and document the reason in the code.


Comparison of assertion methods

Assertion method Syntax Typical scenario elements, but be careful about
as assertion value as Type Converting any to a specific type, DOM operations Low (with overlap checking)
Non-null assertion value! Confirming not null/undefined Medium (skips null checking)
Const assertion value as const Literal constants, enum values None
Double assertions value as unknown as T Forced conversion when types have no overlap High (completely bypasses checking)

Summary