Sub topic 14
Fix the code, the type, or the call site
This chapter assumes you can run npx tsc --noEmit, read a diagnostic's file, line, error code and message chain, and tell assignability errors from missing-property errors. Here you learn to decide where to make the change once you know what the compiler is objecting to. The same error can be removed in several places, and the right place depends on which part of your program is wrong.
Three places to fix an error
Most diagnostics involve two sides: something that produces or supplies a value, and something that declares what it expects. The compiler reports the point where they disagree, but it cannot tell you which side is mistaken. You have three options:
- Fix the code. The logic that produces the value is wrong, and the declared type is correct. The value should change.
- Fix the type. The value is legitimate, but the annotation, interface, or function signature does not describe reality. The declaration should change.
- Fix the call site. Both the function and the value are reasonable on their own. The caller has to adapt, for example by converting, checking, or supplying a missing piece.
A fourth option, silencing the compiler with an assertion or suppression comment, is covered in the next chapter. Treat it as a last resort after you have ruled out these three.
One error, three possible fixes
Consider this program with strict enabled. An order may or may not have a coupon, and the discount function takes a coupon code.
type Order = { id: number; total: number; couponCode?: string };
const discounts: Record<string, number> = { SAVE10: 0.1, SAVE20: 0.2 };
function discountedTotal(order: Order, code: string): number {
const rate = discounts[code] ?? 0;
return order.total * (1 - rate);
}
const order: Order = { id: 1, total: 50 };
console.log(discountedTotal(order, order.couponCode));The compiler reports TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. The argument is optional in Order, but the parameter demands a string.
Fix the call site
If discountedTotal should only run when a coupon exists, the caller is responsible for checking. Narrowing the value at the call site fixes the error and handles the missing case:
const code = order.couponCode;
const total = code === undefined ? order.total : discountedTotal(order, code);
console.log(total);Copying order.couponCode into a const first matters. TypeScript narrows local variables reliably, and property reads can be narrowed too, but a local keeps the check and the use visibly together.
Fix the type
If "no coupon" is a normal input, the function signature is too strict. Change it to say so, and handle the case inside:
function discountedTotal(order: Order, code: string | undefined): number {
const rate = code === undefined ? 0 : (discounts[code] ?? 0);
return order.total * (1 - rate);
}Now every caller can pass order.couponCode directly. The cost is that the function absorbs a case callers used to handle, and a caller who forgets a coupon no longer gets a warning. Use this fix when the "missing" case has one obvious meaning, such as "no discount". Avoid it when each caller would want to handle the case differently.
Fix the code
Sometimes the type is right and the logic is wrong. The error then points at a real bug:
function parsePort(raw: string): number {
const value = Number(raw);
if (Number.isNaN(value)) {
return "invalid";
}
return value;
}TS2322 reports Type 'string' is not assignable to type 'number' on the return "invalid" line. Every caller of parsePort expects a number. A string flowing into arithmetic would produce wrong results at runtime. The fix is to change the code so the invalid case cannot return a bogus value:
function parsePort(raw: string): number {
const value = Number(raw);
if (Number.isNaN(value)) {
throw new Error(`Invalid port: ${raw}`);
}
return value;
}You could instead change the return type to number | string, but that fix pushes the problem into every caller. That is a fix to the wrong place.
Choosing between them
Ask these questions in order. Stop at the first "yes".
| Question | If yes | Typical sign |
|---|---|---|
| Would the program misbehave at runtime with this value? | Fix the code | The error exposes a wrong return, a wrong field name, or a missed branch |
| Is the data valid, but the declaration describes something narrower or different? | Fix the type | An API field is always present but marked optional, or a union lacks a real member |
| Does the function have a clear contract that this caller is breaking? | Fix the call site | Callers pass raw strings, possibly-undefined values, or unvalidated input |
| None of these, and you can justify it in a comment | Assertion or `@ts-expect-error` | The compiler lacks information you can prove, such as a value validated elsewhere |
Two further considerations help break ties.
Count the blast radius. Changing a function signature or shared interface affects every use. Run npx tsc --noEmit --pretty false after the change and compare the error count with the count before. A type change that fixes one error and creates five has moved the problem. A call-site fix touches only one place.
Prefer fixing at the boundary. Data enters your program from outside: user input, JSON, environment variables, network responses. Validating and converting there lets the rest of the code work with precise types. The Number(input) plus Number.isNaN check from the earlier chapters is this pattern. If many call sites need the same conversion, move it into one helper rather than repeating it.
Common wrong fixes
These resolve the diagnostic but not the problem.
- Widening to
anyor a huge union. Changingcode: stringtocode: anyremoves the error and every future check on that parameter. If you need to widen, name the specific members you accept. - Making a property optional to silence a missing-property error.
{ id: 1 }assigned toUserstops failing ifname?: string, but every reader ofuser.namenow gets a TS18048 "possibly undefined" error, or worse, a runtimeundefined. Optional should mean "legitimately absent". - Marking a possibly-undefined value with
!. The non-null assertion removes the error without removing the possibility. Use it only when you can prove the value exists, and say why in a comment. - Editing the type to match the bug. If a function returns the wrong shape because of a typo in a field name, changing the interface to match the typo spreads the typo.
Re-checking the whole project
Fixing one location can reveal or remove other diagnostics, especially when a shared type changes. Make it a habit to run the full check after each fix, not only on the file you edited:
$ npx tsc --noEmit --pretty falseIf the count goes down and no new codes appear, the fix was local. If new errors appear in other files, either the type change was correct and callers now need updating, or the change was in the wrong place. Decide which, using the questions in the table, before continuing.
Exercise
A function getLabel(user: User): string has the body return user.nickname;, where nickname?: string is declared on User. The compiler reports TS2322: Type 'string | undefined' is not assignable to type 'string'. Name the three places you could fix this and which one you would choose if every user without a nickname should display their name.
Show answer
You could fix the code (change the body), the type (change the return type to string | undefined, or make nickname required), or the call site (but there is no caller involved in this error, so that option does not apply here). Since users without a nickname should display name, fix the code: return user.nickname ?? user.name;. The return type remains correct, and no caller has to change.
Exercise
You change a shared interface Settings so timeout is required instead of optional, and the compiler now reports TS2741 in 14 files that build Settings objects. What does that tell you about the choice of fix, and what should you check before deciding whether to keep the change?
Show answer
The 14 errors show that the type change has a large blast radius. Before keeping it, ask whether timeout truly must always be provided (then updating the 14 callers, or adding a default in one factory function, is correct) or whether callers legitimately omit it (then revert to optional and handle undefined where the value is read). Compare the error count before and after, and prefer a single place that supplies the default over repeating it in 14 call sites.