Narrowing and type guards in TypeScript
Teaching the compiler what a value actually is.
type Input = string | number | string[] | null;
function length(input: Input): number {
if (input === null) return 0;
if (typeof input === "string") return input.length;
if (typeof input === "number") return String(input).length;
if (Array.isArray(input)) return input.length;
return 0;
}
function isUser(value: unknown): value is { name: string } {
return typeof value === "object" && value !== null && "name" in value;
}
How it works
typeofandArray.isArraynarrow a union.- Each check removes possibilities from the type.
value is Xdeclares a custom type guard.
Keywords and builtins used here
ArrayInputStringfunctionifnumberreturnstringtypeunknown
The run, in numbers
- Lines
- 13
- Characters to type
- 424
- Tokens
- 108
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 68 seconds.
Step 1 of 4 in Narrowing, step 7 of 23 in Types & annotations.