0
0
Typescriptprogramming~30 mins

Generic conditional constraints in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Generic Conditional Constraints in TypeScript
📖 Scenario: Imagine you are building a small library to handle different types of user inputs. Some inputs are strings, and some are numbers. You want to create a function that behaves differently depending on the type of input it receives, but you want to keep the function generic and type-safe.
🎯 Goal: Build a generic TypeScript function that uses conditional constraints to handle string and number inputs differently, returning a specific message for each type.
📋 What You'll Learn
Create a generic function with a type parameter constrained conditionally
Use conditional types to differentiate behavior for string and number inputs
Return a string message describing the input type and value
Use type-safe code with explicit type annotations
💡 Why This Matters
🌍 Real World
Generic conditional constraints help create flexible and type-safe functions that behave differently based on input types, useful in libraries and frameworks.
💼 Career
Understanding generic constraints and conditional types is important for writing robust TypeScript code in professional software development.
Progress0 / 4 steps
1
Create a generic function with a type parameter
Write a generic function called describeInput with a type parameter T. The function should accept one parameter called input of type T. For now, just return the input as is.
Typescript
Need a hint?

Define a generic function with and a parameter input of type T.

2
Add a conditional type constraint to the generic parameter
Modify the generic type parameter T to extend string | number so that describeInput only accepts strings or numbers.
Typescript
Need a hint?

Use T extends string | number to restrict the generic type.

3
Use a conditional type to return different string messages
Change the return type of describeInput to a conditional type that returns string. Inside the function, use a typeof check on input to return `String input: ${input}` if input is a string, or `Number input: ${input}` if input is a number.
Typescript
Need a hint?

Use typeof inside the function to check the input type and return the correct message.

4
Test the function by printing outputs for string and number inputs
Call describeInput with the string 'hello' and the number 42. Print both results using console.log.
Typescript
Need a hint?

Use console.log to print the results of calling describeInput with 'hello' and 42.