Type assertion (as)

Telling the compiler the type of a value when you know more than it does.

On this page

Example

#
TypeScript
type Lesson = { title: string; minutes: number }

const raw = '{"title":"Grid","minutes":16}'
const lesson = JSON.parse(raw) as Lesson

console.log(lesson.title.toUpperCase(), lesson.minutes)
Result
GRID 16

Definition and usage

#

The assertion value as Type tells the compiler: “trust me, this is a Type”. It doesn’t change the value, and it checks nothing at runtime. It only affects the type at compile time.

Reasonable cases include a DOM element you know is a form field (as HTMLInputElement), or data that another layer of the application has already validated.

An overused assertion is a quiet back door for bugs. If the value actually has a different shape, the program only breaks at runtime. Wherever you can, use narrowing and type guards instead of as.

Syntax

#
Syntax
const value = expression as Type

More examples

#
An assertion doesn’t validate data
TypeScript
const broken = JSON.parse('{"name":"Grid"}') as Lesson

try {
  console.log(broken.title.toUpperCase())
} catch (error) {
  console.log('Runtime error, even though the compiler did not complain')
}
Result
Runtime error, even though the compiler did not complain

Good practices

#
  • Treat as as a last resort. For data from outside, it’s better to check its shape with a type guard.
  • A double assertion as unknown as T almost always means something is wrong with the types.

Related entries

#

Spotted a mistake or missing an example? Write to us.