Bird
Raised Fist0
Typescriptprogramming~30 mins

Type predicates in practice in Typescript - Mini Project: Build & Apply

Choose your learning style10 modes available
Type predicates in practice
📖 Scenario: Imagine you are building a simple app that handles different shapes. Each shape can be a Circle or a Square. You want to write code that checks which shape you have and then calculates the area correctly.
🎯 Goal: You will create a list of shapes, write a type predicate function to check if a shape is a Circle, then use that function to calculate and print the area of each shape.
📋 What You'll Learn
Create a union type called Shape that can be a Circle or a Square.
Create a type predicate function called isCircle that checks if a shape is a Circle.
Use a for loop to go through an array of shapes and calculate the area using the type predicate.
Print the area of each shape with a message.
💡 Why This Matters
🌍 Real World
Type predicates help you write safer code when working with data that can be different types, like shapes, user inputs, or API responses.
💼 Career
Understanding type predicates is important for TypeScript developers to avoid runtime errors and improve code quality in real projects.
Progress0 / 4 steps
1
Create the shapes array
Create a type called Circle with a radius number property, a type called Square with a side number property, and a union type called Shape that can be either Circle or Square. Then create a constant array called shapes with these exact values: a Circle with radius 5, a Square with side 10, and a Circle with radius 3.
Typescript
Hint

Start by defining the types exactly as described, then create the array with the exact objects.

2
Write the type predicate function
Write a function called isCircle that takes a parameter shape of type Shape and returns a type predicate shape is Circle. The function should return true if shape has the property radius, otherwise false.
Typescript
Hint

Use the syntax function isCircle(shape: Shape): shape is Circle and check if radius exists on shape.

3
Calculate areas using the type predicate
Use a for loop with the variable shape to go through the shapes array. Inside the loop, use the isCircle function to check if shape is a Circle. If it is, calculate the area as Math.PI * shape.radius * shape.radius. Otherwise, calculate the area as shape.side * shape.side. Store the area in a variable called area.
Typescript
Hint

Use if (isCircle(shape)) to check the type and calculate area accordingly.

4
Print the area of each shape
Inside the for loop, after calculating the area, write a console.log statement that prints exactly: Area: followed by the area rounded to 2 decimal places using area.toFixed(2).
Typescript
Hint

Use console.log("Area: " + area.toFixed(2)) to print the area with two decimals.

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