How to fix common typescript mistakes

The mistake is usually not on the line with the red underline. TypeScript reports the point where a wrong type finally becomes impossible to ignore, which is often several calls away from where the wrong value was created. Reading the report correctly is most of the repair.

Read the message from the bottom up

The first line names the file and position; the last line usually names the actual conflict: expected this, received that. Start with the conflict, then work backwards to where the value came from.

Hover the variable at the reported position. If the type shown is enormous, an inferred type has grown too complex, and splitting the expression will usually shorten both the type and the message.

Keep the error panel visible while you edit. Closing it to concentrate guarantees you will treat the symptom instead of the cause, and the same error returns under a different line number an hour later.

Symptom: the value is possibly undefined

  • Cause: an optional property, an array access, or a lookup that might miss.
  • Fix: return early when the value is absent, or supply a default in the place where a default makes sense.
  • Avoid: the non-null assertion as a habit, because each one is a promise you may not keep.

If the value truly cannot be missing, the type is lying somewhere upstream, and that is the bug worth fixing.

Symptom: any has spread through the file

One untyped library or one escaped any can silence whole call chains. Find the leak by giving a caller an explicit return type: the compiler will point at the function that cannot satisfy it.

Searching for the keyword is faster than reading, but the explicit return type tells you where the type entered, which is what you need in order to fix it once.

Symptom: types widened when you wanted literals

A let variable, an object literal, or an array without an annotation widens to the general type. That is why a string becomes string instead of the exact value you assigned, and why a status field accepts anything.

  • Use const for values that never change.
  • Add as const to a literal you need to keep narrow.
  • Use satisfies when a value should be checked against a type without losing its precise shape.

Symptom: a property does not exist on a union

You are touching a property before proving which member of the union you have. Narrow first with a tag check, and the property exists on that branch. If the union has no tag, add one; the shape is telling you it needs a discriminator.

If a one-line fix requires changing five files, stop. That is a data model problem wearing a compiler error as a disguise. Redraw the shape first, then let the errors guide the migration.