A jar in the kitchen has a "sugar" label stuck on it. Everyone trusts the label and spoons it into their coffee. If it's actually full of salt, your coffee still tastes salty. The label doesn't change what's in the jar at all.
A type assertion works like the label on that jar, but for TypeScript. You write it with the word as, and it means "trust me, this value is of type X". The value is what's in the jar, the type after as is the label, and TypeScript is the person who trusts the label. TypeScript stops checking and simply believes you, but the value itself doesn't change.
as: you guarantee the type
Sometimes you know more than TypeScript does. HTML elements are a common example. TypeScript doesn't read your HTML file, so document.getElementById("email") is only known as HTMLElement | null: some element, or nothing. The type HTMLElement has no value (what's typed in an input box). So the line el.value = "[email protected]" below gets two errors: el may be null, and HTMLElement has no value.
// Your HTML has <input id="email">
const el = document.getElementById("email")
el.value = "[email protected]"
// error TS18047: 'el' is possibly 'null'.
// error TS2339: Property 'value' does not exist on type 'HTMLElement'.
const input = document.getElementById("email") as HTMLInputElement
input.value = "[email protected]" // OK
as HTMLInputElementmeans "treat this as an input".HTMLInputElement(the type for an<input>element) hasvalue, so the error goes away.- It also removes
nullfrom the type. So you're the one promising the element exists.
A second example: JSON.parse (which turns JSON text into an object) always returns any, because TypeScript can't know what's in a JSON text before the code runs. People often write JSON.parse(text) as User so the result has a type.
An assertion doesn't change the data
Types only exist while TypeScript checks your code. Before the code runs, every type is erased, as User included. Here's the code, then the JavaScript that's left once the types are erased:
type User = { name: string }
const text = '{"age":17,"active":true}'
const data: unknown = JSON.parse(text)
const user = data as User // TypeScript: no error
console.log(user.name.toUpperCase())
// The JS once types are erased
const text = '{"age":17,"active":true}'
const data = JSON.parse(text)
const user = data
console.log(user.name.toUpperCase())
unknown means what's inside isn't known yet, so TypeScript rejects data.name until someone guarantees what's inside. as User is that guarantee. Here's what happens with three different values of text:
text holds |
TypeScript | Console when it runs |
|---|---|---|
{"name":"Budi"} |
no error | BUDI |
{"age":17,"active":true} |
no error | TypeError: Cannot read properties of undefined (reading 'toUpperCase') |
null |
no error | TypeError: Cannot read properties of null (reading 'name') |
For the second and third texts, TypeScript says nothing, then the program crashes (stops with an error) when it runs. The second text has no name, so user.name is undefined. The third text gives null, which has no properties at all. The messages in the table are Chrome's and Node's. Other browsers word them a little differently.
What as rejects, and what passes
as only rejects what's clearly impossible: two types that don't fit each other at all, like string and number:
const n = "17" as number
// error TS2352: Conversion of type 'string' to type 'number' may be a mistake because
// neither type sufficiently overlaps with the other. If this was intentional,
// convert the expression to 'unknown' first.
const m = "17" as unknown as number // no error
m.toFixed(1) // when it runs: TypeError: m.toFixed is not a function
as unknownis always accepted, because any value may be treated asunknown. Thenunknownmay be treated as any type. Soas unknown as number(a double assertion, two assertions in a row) skips every check. The value is still the text"17", so it crashes.- A
!after a value (the non-null assertion) promises "this isn'tnullorundefined". If the result ofdocument.getElementById("titel")!is stored in a variabletitle, TypeScript accepts it. But the id"titel"has a typo, so there's no such element (the result isnull), andtitle.textContent = "Hello"crashes withTypeError: Cannot set properties of null (setting 'textContent').
satisfies: checked, but the type stays
satisfies (since TypeScript 4.9) works the opposite way from as. satisfies checks that a value fits a type, but doesn't replace the type TypeScript guessed from the value.
type Config = { port: number | string }
const a: Config = { port: 3000 }
a.port.toFixed(0)
// error TS2339: Property 'toFixed' does not exist on type 'string | number'.
const b = { port: 3000 } satisfies Config
b.port.toFixed(0) // OK: b.port stays a number
const c = { port: true } satisfies Config
// error TS2322: Type 'boolean' is not assignable to type 'string | number'.
ahas the type annotationConfig, soa.portisstring | number, andtoFixed(a number method) is rejected.bkeeps the type TypeScript guessed, sob.portis anumber.cis rejected, becausetrueis not a string or a number.
Because satisfies really checks, satisfies can't be used on data whose contents aren't known yet. data satisfies User with data: unknown is rejected: error TS1360: Type 'unknown' does not satisfy the expected type 'User'.
Data from outside: check it with a type guard
Data from a server, localStorage (a place to store data in the browser) or user input can't be guaranteed with as, because you only see what's in it when the program runs. The safe way is the type guard from the type narrowing lesson: a function that really checks the contents while the code runs.
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null && "name" in x && typeof x.name === "string"
}
const data: unknown = JSON.parse(text)
if (isUser(data)) {
console.log(data.name.toUpperCase()) // here data: User
} else {
console.log("Not a User")
}
With {"name":"Budi"} it prints BUDI. With {"age":17,"active":true} or null it prints Not a User, with no crash. The typeof and in checks are plain JavaScript, so they stay in the JS and aren't erased.
These are your choices for making sure a value has the right type:
| Way | When to pick it |
|---|---|
satisfies |
Values you write yourself in the code. |
A type guard like isUser |
A small data shape, with one or two properties. |
| A schema library (rules for the shape of data): Zod, Valibot or ArkType | Data from an API or a form with many properties. You write the rules once, and the type comes from those rules. |
as |
Only when the value was already checked another way. |
An example with Zod (npm install zod). The results are the same as with isUser: BUDI for {"name":"Budi"}, and Not a User for the others:
import { z } from "zod"
const UserSchema = z.object({ name: z.string() })
type User = z.infer<typeof UserSchema> // { name: string }
const result = UserSchema.safeParse(JSON.parse(text))
if (result.success) {
console.log(result.data.name.toUpperCase())
} else {
console.log("Not a User")
}
UserSchema is the rule: an object whose name is a string. z.infer takes the type from that rule, and safeParse checks the data while the program runs: result.success is true when the data fits, and result.data holds the data.
⚠️ Lying labels and silenced errors
- Thinking
aschanges the data.asonly changes what TypeScript believes. Text doesn't become a number, and an object doesn't suddenly get aname. - Returning the text instead of the object. In the exercise,
parseJSON('{"name":"Budi"}')must return the object{"name":"Budi"}.return jsonreturns the original text. ReturnJSON.parse(json). - Leaving
: anyas the return type. In the exercise,parseJSONstarts with the return typeany.anyaccepts anything, so even a wrong assertion likeas numberis accepted with no error. With the return typeRecord<string, unknown>, TypeScript rejects it right away:error TS2322: Type 'number' is not assignable to type 'Record<string, unknown>'.TypeScript checks your code, so that error makes the exercise fail. - Using
as unknown asand!to silence errors. The error leaves the editor, but comes back as a crash when the code runs.
TL;DR: as Type (a type assertion) tells TypeScript to believe the value has that type, without checking. The value doesn't change either, because every type is erased before the code runs. as only rejects impossible types (TS2352), like a text treated as a number. as unknown as (a double assertion) and ! (the non-null assertion, a promise that the value isn't null) reject nothing, so mistakes appear as crashes (the program stops with an error) when the code runs. satisfies checks a value you wrote yourself, and keeps the type TypeScript guessed. For data from outside, like data from a server, use a type guard: a function that checks the contents while the code runs. JSON.parse turns JSON text into an object, and the type of its result is any.
⚡ as: you guarantee the type
Write:
const input = document.getElementById("email") as HTMLInputElement
input.value = "[email protected]"
Meaning: The HTML has <input id="email">, but TypeScript doesn't read your HTML. So that element is only known as HTMLElement | null, which has no value. as HTMLInputElement is a type assertion: it means "trust me, it's an input", and TypeScript stops checking.
⚡ A label doesn't change what's inside
Write:
const data: unknown = JSON.parse('{"age":17,"active":true}')
const user = data as User
console.log(user.name.toUpperCase())
Guess first: User is { name: string }, but the data has no name. Does TypeScript report an error?
No. TypeScript says nothing, then the program crashes (stops with an error) while running: TypeError: Cannot read properties of undefined. as User is erased before the code runs, and the data doesn't change.
Meaning: The type after as is only like a label: it changes what TypeScript believes, not the data. as unknown as and the ! mark (a promise that the value isn't null) also only silence errors: the mistake turns into a crash.
⚡ Data from outside: check what's in it
Write:
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null && "name" in x && typeof x.name === "string"
}
Meaning: Data from a server, localStorage or user input can't be guaranteed with as. isUser is a type guard: a function that really checks what's inside while the code runs, because typeof and in stay in the JavaScript. Inside if (isUser(data)), data has the type User.
In the exercise, parseJSON has to turn JSON text into an object, so return JSON.parse(json), not the original text.