Casting

Contents

Casting#

Type assertions (as) tell the compiler to trust the operator. Runtime parse + validate is the safer pattern; the operator reaches for zod (or valibot) instead of asserting on incoming JSON.

Use zod to parse, then z.infer to recover the type.

import {z} from "zod";

const ConfigSchema = z.object({host: z.string(), port: z.number()});
type Config = z.infer<typeof ConfigSchema>;

const config: Config = ConfigSchema.parse(JSON.parse(raw));

For static-only conversion (no runtime check), satisfies keeps the inferred literal type while constraining the structure; prefer it to as for object literals.

const cfg = {host: "example.com", port: 443} satisfies {host: string; port: number};

as should be reserved for the cases the operator cannot prove to the compiler.

const el = document.getElementById("root") as HTMLDivElement;

References#