Sub topic 3
Handle Null and Undefined
Assume you know JavaScript functions, arrays, objects, and npm commands. This chapter assumes TypeScript is already configured with allowJs and a src directory.
Check for Missing Values
With strictNullChecks, null and undefined are separate types. A function that may not find a user should say so:
interface User {
name: string;
age: number;
}
function findUser(users: User[], name: string): User | undefined {
return users.find((user) => user.name === name);
}
const user = findUser([{ name: "Ada", age: 36 }], "Grace");
if (user !== undefined) {
console.log(user.name.toUpperCase());
}The if statement narrows user from User | undefined to User. Calling user.name before that check produces a compiler error.
Narrow Types with Checks
Narrowing means making a type more specific after a runtime check. Use checks that match the data:
value !== undefinedchecks for a missing result.typeof value === "string"checks primitive values."port" in valuechecks for an object property.- A custom type guard can return
value is SomeType.
Avoid solving every error with !. The non-null assertion operator hides a possible runtime failure.
Use `unknown` at Boundaries
JSON, user input, and third-party responses are untrusted. Use unknown, validate the value, and then return a typed object:
interface Config {
port: number;
}
function parseConfig(text: string): Config {
const data: unknown = JSON.parse(text);
if (typeof data !== "object" || data === null) {
throw new Error("Config must be an object");
}
const record = data as Record<string, unknown>;
if (typeof record.port !== "number") {
throw new Error("Config.port must be a number");
}
return { port: record.port };
}A type assertion such as as Record<string, unknown> changes the compiler's view. It does not validate data. Do not replace unknown with any unless you intentionally accept no type checking.
Compile and Increase Checking
Run the compiler after each small conversion:
npx tsc --noEmit
npx tsc
node dist/index.jsTurn checks on in stages. Enable strictNullChecks, fix missing-value paths, then enable noImplicitAny. After those errors are resolved, enable "strict": true and address the remaining errors.
Keep the migration reliable with a linter, tests, and CI. CI should run npx tsc --noEmit so untyped changes cannot merge silently.
Exercise
Why does findUser return User | undefined instead of just User?
Show answer
Array.prototype.find may find no matching element, so the return type records that missing result and requires a check before using the user.