Assertions
| The as keyword | |
| Non-null ! | |
| const assertions | |
| Assertions can lie |
The as keyword
The as keyword tells the compiler to treat a value as a narrower type. It never converts data at runtime, it only changes the static view. Reach for it when you know more than the checker can prove.
const input: unknown = "hi";
const text: string = input as string;
Non-null !
The exclamation mark removes null and undefined from the type in one character. Use it only when logic above guarantees a real value. A wrong mark crashes at runtime with no compiler warning to save you.
function head(items: string[]): string {
const first: string | undefined = items[0];
return first!;
}
const assertions
Appending as const freezes a literal into its narrowest form. Arrays become readonly tuples and strings keep exact text types. Exact literals power safer option unions and config objects.
const verbs = ["get", "post"] as const;
type Verb = (typeof verbs)[number];
Assertions can lie
Assertions bypass checks, so a wrong one compiles cleanly and fails later. Prefer guards and generics that prove the type instead of claiming it. When an assertion survives review, add a comment that states the reason.
const n: unknown = 42;
if (typeof n === "string") {
console.log(n.toUpperCase());
}
Next: Classes
Article author: Arthur Isaev