Questions
What are type guards and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new function that takes a value of an unknown type and needs to perform a different operation depending on the type of the value.
You could use a series of if statements with typeof checks, but this would not be very elegant or type-safe.
The Challenge
Explain what type guards are in TypeScript and how you would use them to solve this problem. What are the key benefits of using type guards?
A junior engineer might not be aware of type guards. They might try to solve this problem by using a series of `if` statements with `typeof` checks, which would be a verbose and error-prone solution.
A senior engineer would know that type guards are the perfect tool for this job. They would be able to explain what type guards are and how to use them to create a function with a dynamic return type.
Step 1: Understand What Type Guards Are
A type guard is a function that returns a boolean value and that has a type predicate as its return type. A type predicate is a special return type that tells the TypeScript compiler that a value has a specific type if the function returns true.
Step 2: Write a Simple Type Guard
Here’s how we can write a simple type guard to check if a value is a string:
function isString(value: unknown): value is string {
return typeof value === "string";
}Step 3: Use the Type Guard
We can use the type guard in an if statement to narrow the type of a value:
function myFunc(myVar: unknown) {
if (isString(myVar)) {
// myVar is now of type string
console.log(myVar.toUpperCase());
}
}The Benefits of Using Type Guards
| Benefit | Description |
|---|---|
| Type Safety | Type guards provide compile-time type safety, which can help you to catch errors early. |
| Readability | Type guards make your code more readable by making it clear what type of data you are working with. |
| Reusability | You can reuse the same type guard in multiple places in your code. |
Practice Question
You want to create a type guard that checks if a value is a `number`. Which of the following would you use?