Bird
Raised Fist0
Typescriptprogramming~10 mins

Type predicates in practice in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Type predicates in practice
Start with unknown type
↓
Call type predicate function
↓
Function returns true or false
Yes No↓
Narrow type
↓
Use narrowed type
↓
End
We start with a value of unknown type, use a type predicate function to check its type, then narrow the type based on the result to safely use it.
Execution Sample
Typescript
function isString(x: unknown): x is string {
  return typeof x === 'string';
}

const val: unknown = "hello";
if (isString(val)) {
  console.log(val.toUpperCase());
}
This code checks if 'val' is a string using a type predicate, then safely calls a string method.
Execution Table
StepVariableType BeforeFunction CallPredicate ResultType AfterAction
1valunknownisString(val)truestringEnter if block
2valstringN/AN/AstringCall val.toUpperCase() -> 'HELLO'
3valstringN/AN/AunknownExit if block
💡 Predicate returned true, type narrowed to string, safe to call string methods
Variable Tracker
VariableStartAfter Step 1After Step 2Final
valunknown ("hello")string ("hello")string ("hello")unknown ("hello")
Key Moments - 2 Insights
Why can we call val.toUpperCase() inside the if block?
Because the type predicate function isString(val) returned true at step 1, so TypeScript knows val is a string inside the if block (see execution_table row 1).
What happens if isString(val) returns false?
If it returns false, the type of val stays unknown outside the if block, so calling string methods would cause an error (not shown in this trace but implied by exit_note).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the type of 'val' after step 1?
Astring
Bunknown
Cnumber
Dboolean
💡 Hint
Check the 'Type After' column in execution_table row 1
At which step is val.toUpperCase() called?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Action' column in execution_table row 2
If isString(val) returned false, what would happen to the type of val?
AIt would become number
BIt would be narrowed to string
CIt would remain unknown
DIt would become boolean
💡 Hint
See key_moments explanation about false predicate result
Concept Snapshot
Type predicates check a value's type at runtime.
Syntax: function fn(x): x is Type { return condition; }
If true, TypeScript narrows the variable's type.
Use inside if to safely access type-specific properties.
If false, type stays original.
Full Transcript
This example shows how a type predicate function 'isString' checks if a variable 'val' is a string. Initially, 'val' has an unknown type. When we call isString(val), it returns true, so TypeScript narrows 'val' to string inside the if block. This lets us safely call string methods like toUpperCase. If the predicate returned false, the type would remain unknown and calling string methods would cause errors. The execution table traces these steps, showing variable types and actions. This helps beginners see how type predicates work in practice.

Practice

(1/5)
1.

What is the main purpose of a type predicate function in TypeScript?

easy
A. To convert one type to another automatically
B. To tell TypeScript the specific type of a variable after a check
C. To declare a new type alias
D. To throw an error if a type is incorrect

Solution

  1. 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.
  2. Step 2: Identify the correct purpose

    It helps TypeScript narrow down types safely after a check, not convert or declare types.
  3. Final Answer:

    To tell TypeScript the specific type of a variable after a check -> Option B
  4. Quick Check:

    Type predicate = type narrowing [OK]
Hint: Type predicates confirm variable types after checks [OK]
Common Mistakes:
  • Thinking type predicates convert types
  • Confusing type predicates with type aliases
  • Assuming type predicates throw errors
2.

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';
}
easy
A. value: string
B. string
C. boolean
D. value is string

Solution

  1. Step 1: Recall type predicate syntax

    A type predicate function returns a boolean and uses the syntax paramName is Type in the return type.
  2. Step 2: Match the syntax to the example

    The function returns true if value is a string, so the return type is value is string.
  3. Final Answer:

    value is string -> Option D
  4. Quick Check:

    Type predicate syntax = param is Type [OK]
Hint: Use 'param is Type' as return type for type predicates [OK]
Common Mistakes:
  • Using just 'boolean' as return type
  • Writing 'value: string' instead of 'value is string'
  • Returning 'string' as type predicate
3.

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);
medium
A. [1, 3]
B. [1, 'two', 3]
C. ['two']
D. []

Solution

  1. Step 1: Understand the filter with type predicate

    The isNumber function returns true only for numbers, so filter keeps only numbers.
  2. Step 2: Apply filter to the array

    From [1, 'two', 3], only 1 and 3 pass the check, so numbers is [1, 3].
  3. Final Answer:

    [1, 3] -> Option A
  4. Quick Check:

    Filter with type predicate keeps matching types [OK]
Hint: Filter with type predicate keeps only matching types [OK]
Common Mistakes:
  • Assuming filter returns original array
  • Thinking it returns only strings
  • Confusing type predicate with type casting
4.

Identify the error in this type predicate function and choose the fix:

function isBoolean(value: unknown): boolean {
return typeof value === 'boolean';
}
medium
A. Change return type to value is boolean
B. Change return type to boolean | undefined
C. Add explicit cast inside function
D. No error, function is correct

Solution

  1. Step 1: Check the return type for type predicate

    The function returns a boolean but does not use the type predicate syntax value is boolean.
  2. Step 2: Fix the return type

    To inform TypeScript about the type, the return type must be value is boolean, not just boolean.
  3. Final Answer:

    Change return type to value is boolean -> Option A
  4. Quick Check:

    Type predicate needs 'param is Type' return type [OK]
Hint: Use 'param is Type' for type predicate return type [OK]
Common Mistakes:
  • Using plain boolean as return type
  • Adding unnecessary casts
  • Assuming no fix needed
5.

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?
hard
A. const strings = mixedArray.map(x => x as string);
B. const strings = mixedArray.filter(x => typeof x === 'string');
C. const strings = mixedArray.filter(isString);
D. const strings = mixedArray.filter(x => x instanceof String);

Solution

  1. Step 1: Understand the goal

    We want to get only strings from a mixed array safely, with TypeScript knowing the type.
  2. Step 2: Use type predicate in filter

    Using filter(isString) uses the type predicate to narrow type safely, so strings is typed as string[].
  3. 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 because instanceof String checks object wrappers, not primitives. const strings = mixedArray.map(x => x as string); casts all elements to string unsafely.
  4. Final Answer:

    const strings = mixedArray.filter(isString); -> Option C
  5. Quick Check:

    Use type predicate function in filter for safe extraction [OK]
Hint: Filter with type predicate narrows type safely [OK]
Common Mistakes:
  • Using instanceof String instead of typeof
  • Casting all elements without filtering
  • Not using type predicate for type safety
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard