Type assertions, non-null, and satisfies

Intermediate · 21 min

Overriding the checker with `as` and `!` when you know more than it does, and checking a value with `satisfies` without losing its precise type.

Before thisType guards and assertion functionsNull, undefined, and strict null checksany, unknown, never, and voidType annotations and type inference

tapaScript by Tapas Adhikary · 21 min

Type assertions, non-null, and satisfies

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by tapaScript by Tapas AdhikaryReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Narrowing proves a type with a runtime check; a type assertion with `as` just tells the checker to use the type you name, and nothing at runtime checks it.
  • `as` only allows conversions where one type is assignable to the other, which blocks obvious mistakes like `"42" as number`; going through `unknown` first removes even that check and should be rare.
  • The non-null operator `x!` is an assertion that removes `null` and `undefined` from `x`'s type, and if you're wrong, the crash happens later, away from the line that caused it.
  • Prefer a narrowing check or an assertion function wherever a wrong guess should fail loudly; keep `as` and `!` for facts the checker can't see but you can, such as the element type of a known DOM node.
  • `value satisfies T` checks that a value matches `T`, including excess property checks, but leaves the value's own inferred type in place, so literal keys and precise member types survive.
  • Use an annotation when you want the variable to have the wider type, and `satisfies` when you want the check without the widening.

When you know more than the checker

Everything so far in this group has been about earning a narrower type: write a check, and the checker follows it. Sometimes you already know the answer and there’s no sensible check to write. Your HTML has an <input id="email">. document.getElementById can’t know that, so it returns HTMLElement | null:

const el = document.getElementById("email");
el.value;
// error: 'el' is possibly 'null'.
// error: Property 'value' does not exist on type 'HTMLElement'.

TypeScript gives you two override tools for this, as and !. Both are compile-time only. They change what the checker believes, never what the program does.

as: type assertions

const input = document.getElementById("email") as HTMLInputElement;
input.value; // input: HTMLInputElement

type Config = { port: number };
const config = JSON.parse('{"port": 3000}') as Config;

as tells the checker to use the type you name. It disappears from the emitted JavaScript, so nothing checks that the element really is an input or that the JSON really has a port. Compare that with narrowing: if (el instanceof HTMLInputElement) checks at runtime and can’t be wrong. An assertion is a promise you’re making on the program’s behalf.

There’s one safety rail. An assertion must go from a type to a wider or narrower version of itself. Unrelated types are rejected:

const n = "42" as number;
// error TS2352: Conversion of type 'string' to type 'number' may be a mistake
//               because neither type sufficiently overlaps with the other.

You can force it with a double assertion, "42" as unknown as number, since anything converts to and from unknown. That turns the checker off for that expression. It’s occasionally needed in test fixtures or around badly typed libraries, and in application code it’s almost always a sign the types are wrong somewhere else.

as const looks similar but is a different tool. It asks for the narrowest literal type rather than overriding anything, and it was covered in the readonly lesson.

!: the non-null assertion

The most common assertion is “this isn’t null”, so it gets its own syntax. A postfix ! removes null and undefined from an expression’s type:

const app = document.getElementById("app")!; // app: HTMLElement
app.textContent = "Hello";

const counts = new Map<string, number>([["a", 1]]);
if (counts.has("a")) {
  const a = counts.get("a")!; // a: number
}

The Map case is typical. You checked has, but the checker doesn’t link has to get, so get still returns number | undefined.

The risk with ! is where it fails. If you’re wrong, no error happens on the line with the !. The null travels on until something reads a property, possibly in another function, and the stack trace points there. Think of it like signing off a delivery without opening the box: the problem surfaces whenever someone finally does.

So reach for the honest options first. if (!app) throw new Error("#app missing") narrows just as well and fails on the right line. The assertion functions from the previous lesson make the same idea reusable. Keep ! for facts that are certain and local.

satisfies: checking without widening

The third operator solves a different problem. Say you have a table of routes and want each entry checked against a Route type:

type Route = { path: string; auth?: boolean };

const routes: Record<string, Route> = {
  home: { path: "/" },
  settings: { path: "/settings", auth: true },
};

routes.setings; // no error: any string key is allowed

The annotation did check the entries, and then it replaced the object’s type with Record<string, Route>. The actual keys are forgotten, so a typo compiles. Leave the annotation off and you keep the keys but lose the check.

satisfies gives you both:

const routes = {
  home: { path: "/" },
  settings: { path: "/settings", auth: true },
} satisfies Record<string, Route>;

routes.settings.path; // fine
routes.setings;
// error: Property 'setings' does not exist on type '{ home: ...; settings: ...; }'.
//        Did you mean 'settings'?

The object is checked against Record<string, Route>, including excess property checks, so { path: "/", auht: true } is still caught. But the variable keeps its own inferred type.

The same thing helps with unions. Given type Color = string | [number, number, number], an annotated Record<string, Color> makes palette.primary a Color, so palette.primary.toUpperCase() fails. With satisfies, palette.primary stays a string.

The rule of thumb: annotate when you want the variable to have the wider type, use satisfies when you only want to be checked against it.

About the video

Tapas Adhikary’s video works through as with DOM and untyped-JSON examples, double assertion through unknown, as const, and then satisfies on a realistic config object. It doesn’t cover the non-null ! operator, which the section above handles; Dave Gray’s video, linked below, has a dedicated non-null assertions chapter, and Matt Pocock’s short clip is a sharp summary of annotation versus satisfies.

Check yourself

  1. 01What is the difference between narrowing with `if (typeof x === "string")` and writing `x as string`?

    The `typeof` check runs at runtime and proves the type, so the narrowing is correct. `as string` is erased at compile time; it just instructs the checker to treat `x` as a string, and if `x` is actually something else, nothing stops it.

  2. 02Why does `"42" as number` fail to compile while `"42" as unknown as number` compiles?

    An assertion is only allowed when one type is assignable to the other, and `string` and `number` don't overlap, so TypeScript reports a likely mistake. Every type is assignable to `unknown` and `unknown` can be asserted to anything, so the double assertion bypasses that check. The result is still a string at runtime.

  3. 03What does `document.getElementById("app")!` do, and what happens if no element has that id?

    The `!` removes `null` from the return type, so the result is `HTMLElement`. It emits no runtime check, so if the element is missing the value is still `null`, and the error comes later, when something reads a property of it.

  4. 04Given `const routes: Record<string, Route> = { home: { path: "/" } }`, why does `routes.hmoe` compile, and how does `satisfies` change that?

    The annotation gives `routes` the type `Record<string, Route>`, so any string key is allowed and the actual key names are forgotten. With `satisfies Record<string, Route>` instead, the object is still checked against `Route`, but `routes` keeps its inferred type with exactly the keys `home` and so on, so `routes.hmoe` is an error.

  5. 05When should a variable get a type annotation rather than `satisfies`?

    When you want the variable to have the wider type, for instance a `let` that will later hold other values of that type, or a value whose details callers shouldn't depend on. `satisfies` suits constants where you want both the check and the precise inferred type.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark