Primitives guard
- TypeScript course
- Advanced
- Lesson 39/57
- 4 min
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";
}Practice 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)).
Starter code
// isString ve isNumber guard fonksiyonlarını tanımla (typeof ile)
// process(v: unknown): string fonksiyonunu guard'larla yaz
// process("hello"), process(42), process(true) sonuçlarını yazdırSample 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));Expected output
HELLO 42 unknown
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which operator is used when writing type guards for primitive types?
- instanceof
- in
- typeof Correct answer
- as
Explanation: For primitive types (string, number, boolean) the typeof operator is used; a guard is written with a check like typeof x === "string".
2 isNumber primitive guard
function isNumber(x: unknown): ____ {
return typeof x === "number";
}
function isNumber(x: unknown): x is number {
return typeof x === "number";
}
Explanation: The x is number predicate tells TypeScript that x is a number when the function returns true, providing narrowing.
3 Primitives guard parts
| Term | Meaning |
|---|---|
typeof |
primitive type check |
isString(x) |
narrows to string |
isNumber(x) |
narrows to number |
x is T |
predicate return type |