Lessons · TypeScript · unknown makes you check first
Anything in, nothing out until checked
unknown accepts any value but allows no operation on it until you narrow it. It is any with the safety kept.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
JSON.parse, message events, catch clauses: data whose shape you cannot know at compile time. unknown makes the check exist instead of hoping.
How to think about it
Type the boundary value as unknown, then narrow with typeof, instanceof, in, or a guard. Each check unlocks the next operation.
Worked example
let v: unknown = JSON.parse("{\"name\":\"ada\"}");Could be anything.v.name;Error: unknown must be narrowed first.
if (typeof v === "object" && v !== null && "name" in v) { console.log((v as { name: string }).name); }Checked, then used.Your turn
Accept anything, allow nothing until checked.
function handle(input: ) { if (typeof input === "string") { return input.trim(); } }Solve one with the compiler running
The trap
Reaching for any to silence an unknown error deletes the safety the error was pointing at. Narrow instead.
Practise unknown makes you check first on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.