Questions
What are generics and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a fintech company. You are writing a new function that needs to work with a variety of different data types.
You could write a separate function for each data type, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.
The Challenge
Explain what generics are in TypeScript and how you would use them to solve this problem. What are the key benefits of using generics?
A junior engineer might not be aware of generics. They might try to solve this problem by using the `any` type, which would not be type-safe.
A senior engineer would know that generics are the perfect tool for this job. They would be able to explain what generics are and how to use them to write type-safe code that can work with a variety of different data types.
Step 1: Understand What Generics Are
Generics are a feature of TypeScript that allows you to write code that is type-safe and can work with a variety of different data types.
Step 2: Write a Simple Generic Function
Here’s how we can write a simple generic function that takes a value of any type and returns it:
function identity<T>(arg: T): T {
return arg;
}In this example, T is a type parameter that can be replaced with any type.
Step 3: Use the Generic Function
We can use the generic function with any type:
let output1 = identity<string>("myString");
let output2 = identity<number>(123);The Benefits of Using Generics
| Benefit | Description |
|---|---|
| Type Safety | Generics provide compile-time type safety, which can help you to catch errors early. |
| Reusability | You can reuse the same generic class or method with a variety of different data types. |
| Readability | Generics make your code more readable by making it clear what types of data are being used. |
Generic Constraints
You can use a generic constraint to limit the types that can be used with a generic function or class.
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}In this example, the loggingIdentity function will only accept types that have a length property.
Practice Question
You want to write a generic function that can accept any type of `Array`. Which of the following would you use?