When TS can't prove a type but you know more: • as assertions: tell TS to treat a value as a narrower type (use sparingly) • non-null assertion (!): assert value is not null/undefined • satisfies: checks a value against a type without widening literals • definite assignment (!:) let TS know a class/var will be assigned before use Prefer narrowing and satisfies over blunt assertions for safety. **Why it matters:** • Assertions can hide real bugs—use them after runtime checks, not before • satisfies keeps literal precision while still validating shape • Definite assignment (!) should be rare; initialize in constructors instead when possible
const el = document.getElementById("email") as HTMLInputElement;// 'as' assertion
const email = document.getElementById("email") as HTMLInputElement;
email.value = "hi@example.com";
// non-null assertion
declare const maybeUser: { name: string } | undefined;
const username = maybeUser!.name;
// satisfies keeps literal precision
const config = {
env: "prod",
retry: 3,
} satisfies { env: "dev" | "prod"; retry: number };
// definite assignment
class Store {
private cache!: Map<string, string>;
init() {
this.cache = new Map();
}
}
Understanding Assertions, Non-Null, satisfies is fundamental to mastering TypeScript. Practice with the examples above and experiment with variations to solidify your knowledge.