0
0
Typescriptprogramming~30 mins

Never type and unreachable code in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Never type and unreachable code
📖 Scenario: You are writing a TypeScript program that uses the never type to handle impossible cases. This helps catch errors early and avoid unreachable code.
🎯 Goal: Build a TypeScript function that uses the never type to handle unexpected input and demonstrate unreachable code detection.
📋 What You'll Learn
Create a function with a switch statement on a string parameter
Add a never type function to handle impossible cases
Use the never type function in the switch default case
Print the result of calling the function with valid and invalid inputs
💡 Why This Matters
🌍 Real World
Using the <code>never</code> type helps developers catch bugs early by ensuring all possible cases are handled, especially in complex decision logic.
💼 Career
Understanding unreachable code and the <code>never</code> type is important for writing robust TypeScript code in professional software development.
Progress0 / 4 steps
1
Create a function with a switch statement
Create a function called getColorCode that takes a parameter color of type string. Inside the function, write a switch statement on color with cases for 'red', 'green', and 'blue'. Return '#FF0000' for 'red', '#00FF00' for 'green', and '#0000FF' for 'blue'.
Typescript
Need a hint?

Use a switch statement with case labels for each color and return the matching hex code string.

2
Add a never type function for impossible cases
Create a function called assertNever that takes a parameter value of type never and throws an Error with the message 'Unexpected value: ' + value.
Typescript
Need a hint?

The assertNever function should accept only never type and throw an error with the unexpected value.

3
Use the never type function in the switch default case
Modify the getColorCode function to add a default case in the switch statement. In the default case, call assertNever(color as never) to handle unreachable code.
Typescript
Need a hint?

Add a default case that calls assertNever with color as never to catch unreachable cases.

4
Print the result of calling the function
Write two console.log statements. The first calls getColorCode('red') and prints the result. The second calls getColorCode('yellow') inside a try block and catches the error to print 'Error caught: ' + error.message.
Typescript
Need a hint?

Use console.log to print the color code for 'red'. Use a try-catch block to catch and print the error message for 'yellow'.