Avoiding any, Understanding never, and Assertions
any opts out of checking and can spread unsafety through a codebase. unknown is a safer top type. never represents an impossible value, often appearing when a function always throws or when a union has been exhaustively narrowed. Type assertions such as value as User tell the compiler to trust you; they do not convert or validate the value.
Use assertions only when you have evidence the compiler cannot express, such as knowledge from a validated boundary or a DOM lookup with a known element type. Keep assertions local, and avoid double assertions such as as unknown as X except in carefully justified interop code.
Use never for exhaustive checks
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
default: {
const impossible: never = shape;
return impossible;
}
}
}💡 After both variants are handled,
shape should be never. If another shape is added and not handled, the assignment reports an error.Key Takeaways
anydisables checks;unknownrequires narrowing.neveris useful for impossible states and exhaustiveness.- Assertions change the compiler's view, not the runtime value.
Knowledge Check
Does `value as User` validate the value at runtime?