Hone

Lessons · TypeScript · any turns the checking off

any turns the checker off

A value typed any can do anything: any property, any call, no errors. It compiles, then crashes at runtime. unknown is the safe alternative.

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

One any at the edge spreads: a function returning any makes every result any, and a whole module quietly loses its types.

How to think about it

Type external data as unknown and narrow it. Reach for any only to silence a third-party type you cannot fix, and comment why.

Worked example

let x: any = 5;
Checking is off for x.
x.foo.bar();
No compile error, and a crash at runtime: 5 has no foo.
let y: unknown = 5;
The safe version.
y.foo;
Error: unknown must be narrowed before use.

Your turn

Accept anything, but force a check before use.

function parse(input: ): number { return typeof input === "number" ? input : 0; }

The trap

noImplicitAny catches the anys you did not write; it cannot catch the ones you did. Search for ': any' in a codebase and each one is a hole.

Practise any turns the checking off on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.