0
0
Typescriptprogramming~30 mins

Generic type variance in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Generic Type Variance in TypeScript
📖 Scenario: You are building a simple system to manage different types of notifications in an app. Notifications can be general messages or special alerts with extra details.
🎯 Goal: Learn how to use generic types with variance in TypeScript to safely handle different notification types.
📋 What You'll Learn
Create a generic interface for notifications
Add a helper type to control variance
Implement a function that accepts notifications with specific variance
Print the notification messages
💡 Why This Matters
🌍 Real World
Generic type variance helps in building flexible and safe APIs that work with different data shapes without losing type safety.
💼 Career
Understanding variance is important for TypeScript developers working on large codebases or libraries where generic types are common.
Progress0 / 4 steps
1
Create a generic interface for notifications
Create a generic interface called Notification<T> with a property message of type string and a property details of type T.
Typescript
Need a hint?

Use interface Notification<T> and define message and details inside.

2
Add a helper type to control variance
Create a type alias called ReadonlyNotification<T> that makes the Notification<T> properties readonly.
Typescript
Need a hint?

Use a mapped type with readonly and keyof to make properties readonly.

3
Implement a function that accepts readonly notifications
Write a function called printNotification that takes a parameter notif of type ReadonlyNotification<T> and logs notif.message to the console.
Typescript
Need a hint?

Define a generic function with parameter type ReadonlyNotification<T> and use console.log to print the message.

4
Create notifications and print their messages
Create a variable alertNotification of type Notification<{ level: string }> with message set to 'Warning!' and details set to { level: 'high' }. Then call printNotification with alertNotification.
Typescript
Need a hint?

Define alertNotification with the exact type and values, then call printNotification(alertNotification).