Type predicates help your program know exactly what type a value is. This makes your code safer and easier to understand.
Type predicates in practice in Typescript
function isString(value: unknown): value is string { return typeof value === 'string'; }
The value is string part is the type predicate. It tells TypeScript what type the value has if the function returns true.
Type predicates always return a boolean (true or false).
function isNumber(value: unknown): value is number { return typeof value === 'number'; }
function isArray(value: unknown): value is any[] { return Array.isArray(value); }
function isUser(obj: any): obj is { name: string; age: number } { return typeof obj.name === 'string' && typeof obj.age === 'number'; }
This program uses a type predicate function isUser to check if each item in the data array is a User. It prints user info only for valid users.
type User = { name: string; age: number };
function isUser(obj: any): obj is User {
return typeof obj === 'object' && obj !== null &&
typeof obj.name === 'string' && typeof obj.age === 'number';
}
const data: unknown[] = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 'unknown' },
'hello',
{ name: 'Charlie', age: 25 }
];
for (const item of data) {
if (isUser(item)) {
console.log(`${item.name} is ${item.age} years old.`);
} else {
console.log('Not a valid user:', item);
}
}Type predicates help TypeScript understand your code better and catch mistakes early.
Always return a boolean from your type predicate functions.
Use type predicates when you want to safely work with values that might have different types.
Type predicates tell TypeScript what type a value has after a check.
They return true or false and help avoid errors.
Use them to safely handle values with uncertain types.
Practice
What is the main purpose of a type predicate function in TypeScript?
Solution
Step 1: Understand what a type predicate does
A type predicate function returns a boolean and tells TypeScript the type of a variable when true.Step 2: Identify the correct purpose
It helps TypeScript narrow down types safely after a check, not convert or declare types.Final Answer:
To tell TypeScript the specific type of a variable after a check -> Option BQuick Check:
Type predicate = type narrowing [OK]
- Thinking type predicates convert types
- Confusing type predicates with type aliases
- Assuming type predicates throw errors
Which of the following is the correct syntax for a type predicate function that checks if a value is a string?
function isString(value: unknown): ??? {
return typeof value === 'string';
}Solution
Step 1: Recall type predicate syntax
A type predicate function returns a boolean and uses the syntaxparamName is Typein the return type.Step 2: Match the syntax to the example
The function returns true ifvalueis a string, so the return type isvalue is string.Final Answer:
value is string -> Option DQuick Check:
Type predicate syntax = param is Type [OK]
- Using just 'boolean' as return type
- Writing 'value: string' instead of 'value is string'
- Returning 'string' as type predicate
What will be the output of this TypeScript code?
function isNumber(value: unknown): value is number {
return typeof value === 'number';
}
const data: unknown[] = [1, 'two', 3];
const numbers = data.filter(isNumber);
console.log(numbers);Solution
Step 1: Understand the filter with type predicate
TheisNumberfunction returns true only for numbers, sofilterkeeps only numbers.Step 2: Apply filter to the array
From[1, 'two', 3], only 1 and 3 pass the check, sonumbersis[1, 3].Final Answer:
[1, 3] -> Option AQuick Check:
Filter with type predicate keeps matching types [OK]
- Assuming filter returns original array
- Thinking it returns only strings
- Confusing type predicate with type casting
Identify the error in this type predicate function and choose the fix:
function isBoolean(value: unknown): boolean {
return typeof value === 'boolean';
}Solution
Step 1: Check the return type for type predicate
The function returns a boolean but does not use the type predicate syntaxvalue is boolean.Step 2: Fix the return type
To inform TypeScript about the type, the return type must bevalue is boolean, not justboolean.Final Answer:
Change return type to value is boolean -> Option AQuick Check:
Type predicate needs 'param is Type' return type [OK]
- Using plain boolean as return type
- Adding unnecessary casts
- Assuming no fix needed
Given this code, what is the best way to safely extract all strings from a mixed array using a type predicate?
type Mixed = (string | number | boolean)[];
function isString(value: unknown): value is string {
return typeof value === 'string';
}
const mixedArray: Mixed = ['hello', 42, true, 'world'];
// What code extracts only strings safely?
Solution
Step 1: Understand the goal
We want to get only strings from a mixed array safely, with TypeScript knowing the type.Step 2: Use type predicate in filter
Usingfilter(isString)uses the type predicate to narrow type safely, sostringsis typed asstring[].Step 3: Compare other options
const strings = mixedArray.filter(x => typeof x === 'string'); also works and does narrow type for TypeScript, but does not use the provided type predicate function. const strings = mixedArray.filter(x => x instanceof String); is incorrect becauseinstanceof Stringchecks object wrappers, not primitives. const strings = mixedArray.map(x => x as string); casts all elements to string unsafely.Final Answer:
const strings = mixedArray.filter(isString); -> Option CQuick Check:
Use type predicate function in filter for safe extraction [OK]
- Using instanceof String instead of typeof
- Casting all elements without filtering
- Not using type predicate for type safety
Ready to prove it?
Pass the test and this pattern moves unknown
