0
0
Typescriptprogramming~15 mins

Custom type guard functions in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom type guard functions
📖 Scenario: You are working on a TypeScript project where you receive data that can be either a string or a number. You want to safely check the type of the data before using it.
🎯 Goal: Build custom type guard functions to check if a value is a string or a number, then use these functions to safely handle the data.
📋 What You'll Learn
Create a variable with mixed type data
Create two custom type guard functions: isString and isNumber
Use these type guard functions in an if statement to check the data type
Print the type and value of the data using the type guards
💡 Why This Matters
🌍 Real World
Custom type guards help you safely work with data that can have multiple types, such as user input or API responses.
💼 Career
Knowing how to write type guards is important for TypeScript developers to avoid runtime errors and improve code safety.
Progress0 / 4 steps
1
Create a variable with mixed type data
Create a variable called data and assign it the value "hello" with the type string | number.
Typescript
Need a hint?

Use let data: string | number = "hello"; to declare the variable.

2
Create custom type guard functions
Create two functions: isString and isNumber. Each should take a parameter value of type unknown and return a type predicate: value is string for isString and value is number for isNumber. Use typeof inside each function to check the type.
Typescript
Need a hint?

Use typeof value === "string" and typeof value === "number" inside the functions.

3
Use type guard functions to check data type
Write an if statement that uses isString(data) to check if data is a string, and an else if statement that uses isNumber(data) to check if data is a number.
Typescript
Need a hint?

Use if (isString(data)) { ... } and else if (isNumber(data)) { ... }.

4
Print the type and value using type guards
Inside the if block for isString(data), write console.log(`Data is a string: ${data}`). Inside the else if block for isNumber(data), write console.log(`Data is a number: ${data}`).
Typescript
Need a hint?

Use console.log(`Data is a string: ${data}`) and console.log(`Data is a number: ${data}`).