TypeScript
Primitives guard
Learn to write guards for primitive types.
Primitives guard
When writing type guards for primitive types, the typeof operator is used. Helper functions like isString, isNumber, isBoolean make common typeof checks reusable. This reduces code duplication and makes narrowing consistent.
function isString(x: unknown): x is string {
return typeof x === "string";
}
function isNumber(x: unknown): x is number {
return typeof x === "number";
}
function isBoolean(x: unknown): x is boolean {
return typeof x === "boolean";
}
Multiple guards
Multiple primitive guards can be combined to perform complex narrowing. For example, to check if a value is a string or number, use isString(v) || isNumber(v). Each guard narrows to the correct type in its branch.
function process(v: unknown): string {
if (isString(v)) {
return v.toUpperCase(); // string
}
if (isNumber(v)) {
return v.toFixed(0); // number
}
return "unknown";
}
Exercise Handle unknown with primitive guards
Define isString(x: unknown): x is string and isNumber(x: unknown): x is number guard functions (each with a typeof check). Write a process(v: unknown): string function: if isString(v) is true, return v.toUpperCase(); else if isNumber(v) is true, return v.toFixed(0); else return "unknown". Print results via console.log(process("hello")), console.log(process(42)), and console.log(process(true)).
Show example solution
function isString(x: unknown): x is string {
return typeof x === "string";
}
function isNumber(x: unknown): x is number {
return typeof x === "number";
}
function process(v: unknown): string {
if (isString(v)) {
return v.toUpperCase();
}
if (isNumber(v)) {
return v.toFixed(0);
}
return "unknown";
}
console.log(process("hello"));
console.log(process(42));
console.log(process(true));
Test yourself
-
Which operator is used when writing type guards for primitive types?
Show answer
typeof — For primitive types (string, number, boolean) the typeof operator is used; a guard is written with a check like typeof x === "string".
-
isNumber primitive guard
function isNumber(x: unknown): ____ {
return typeof x === "number";
}
Show answer
function isNumber(x: unknown): x is number {
return typeof x === "number";
}
-
Primitives guard parts
- typeof
- primitive type check
- isString(x)
- narrows to string
- isNumber(x)
- narrows to number
- x is T
- predicate return type
Next lesson: Summary - Type guards