Learning on Web Dev Open is free for all.

Systems Thinking > TypeScript as a design toolWhen TypeScript is lying to you
Phase 03TypeScript as a design tool165 of 434

When TypeScript is lying to you

any, as, the non-null assertion and array indexing. Four ways the compiler tells you something is fine when it has no idea.

Concept13 minAI adversary

any switches the checker off for everything it touches and spreads outwards through every expression it participates in. unknown is the honest version: it accepts anything and forces a check before use, which is what you actually wanted in almost every place any got written. The non-null assertion is a claim you are making with no evidence, and it is right until the day the API returns null.

as is not a conversion. It tells the compiler to stop disagreeing, changes nothing at runtime, and is the mechanism by which a wrong belief about your data gets locked in. There are legitimate uses: narrowing a value you have genuinely proven, working around a library type that is wrong, and both deserve a comment saying which.

The quietest lie is built in. arr[0] is typed as the element type, not element-or-undefined, even on an empty array. noUncheckedIndexedAccess fixes this and is off by default because turning it on in an existing codebase produces hundreds of errors, most of which are real. Turn it on in anything new. Do the same for strict, exactOptionalPropertyTypes and noImplicitOverride while the file count is small.

You should now be able to

  • Name the escape hatches and their real cost
  • Turn on the flag that fixes the array indexing lie
Ask the community

Loading…