0
0
Typescriptprogramming~15 mins

Extract type in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Extract Type with TypeScript
📖 Scenario: You are working on a TypeScript project where you have a union type representing different user roles. You want to create a new type that extracts only the admin roles from this union.
🎯 Goal: Build a TypeScript program that uses the Extract utility type to create a new type containing only the admin roles from a union type.
📋 What You'll Learn
Create a union type called UserRoles with the exact values: 'admin', 'user', 'guest', 'superadmin'
Create a type called AdminRoles that extracts only 'admin' and 'superadmin' from UserRoles using the Extract utility type
Create a variable called adminRole of type AdminRoles and assign it the value 'admin'
Print the value of adminRole to the console
💡 Why This Matters
🌍 Real World
Extracting specific types from unions helps keep your code safe and clear when working with different categories or roles in applications.
💼 Career
Understanding TypeScript utility types like <code>Extract</code> is important for writing maintainable and type-safe code in professional frontend and backend development.
Progress0 / 4 steps
1
Create the union type UserRoles
Create a union type called UserRoles with these exact string values: 'admin', 'user', 'guest', and 'superadmin'.
Typescript
Need a hint?

Use the | symbol to combine string literals into a union type.

2
Create the extracted type AdminRoles
Create a type called AdminRoles that uses the Extract utility type to extract only 'admin' and 'superadmin' from the UserRoles union type.
Typescript
Need a hint?

Use Extract<UnionType, Subset> to get only the subset of types you want.

3
Create a variable of type AdminRoles
Create a variable called adminRole of type AdminRoles and assign it the value 'admin'.
Typescript
Need a hint?

Declare the variable with const and specify its type after the colon.

4
Print the adminRole variable
Write a console.log statement to print the value of the variable adminRole.
Typescript
Need a hint?

Use console.log(adminRole); to print the value.