Sub topic 2
Fixing TypeScript Type Mismatches
This chapter assumes basic JavaScript, TypeScript annotations, interfaces, union types, and terminal use with Node.js and npm.
Fixing assignments and calls
TypeScript checks assignability: whether a value can safely be used where a type is expected. An assignment error usually has code TS2322. A function-call error usually has code TS2345.
function double(n: number): number {
return n * 2;
}
const input: string = "21";
double(input);The function requires a number, but input is a string. Convert and validate the value at the boundary where it enters your program.
function double(n: number): number {
return n * 2;
}
const input: string = "21";
const parsed = Number(input);
if (Number.isNaN(parsed)) {
throw new Error(`Not a number: ${input}`);
}
console.log(double(parsed));Do not fix this by asserting input as number. An assertion changes the compiler’s belief without converting the runtime value.
Missing and unknown properties
TS2741 means a required property is missing.
interface User {
id: number;
name: string;
}
const user: User = { id: 1 };Add the property, or mark it optional if a user can validly lack it:
interface User {
id: number;
name?: string;
}TS2339 means you accessed a property that the type does not define. Check the property name and the declared type before changing the type.
Strict mode and changed errors
strict: true enables related checks, including strict null checks and implicit-any checks.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noEmit": true
},
"include": ["src"]
}With strict null checks enabled, APIs that may fail report that possibility instead of hiding it.
Possibly undefined: narrow the value
Array.find returns either an element or undefined. TS18048 reports unsafe use of that result.
const names: string[] = ["ada", "alan"];
const first = names.find((n) => n.startsWith("a"));
if (first !== undefined) {
console.log(first.length);
} else {
console.log("no match");
}The if condition narrows first from string | undefined to string inside the first branch.
Exercise
What should you do before accessing a value returned by Array.find?
Show answer
Check whether it is undefined, then use it only in the branch where TypeScript has narrowed it to the element type.