0
0
Typescriptprogramming~30 mins

Non-distributive conditional types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Non-distributive conditional types
📖 Scenario: Imagine you are building a TypeScript utility to check if a type is exactly string or not, without distributing over unions. This helps when you want to treat unions as a whole instead of their parts.
🎯 Goal: You will create a non-distributive conditional type called IsExactlyString that returns true if the type is exactly string, and false otherwise. Then you will test it with different types.
📋 What You'll Learn
Create a generic type called IsExactlyString that takes a type parameter T.
Use a tuple wrapper to prevent distribution in the conditional type.
Return true if T is exactly string, else false.
Create variables with types using IsExactlyString for string, number, and string | number.
Print the types of these variables to verify the results.
💡 Why This Matters
🌍 Real World
Non-distributive conditional types help when you want to check or transform types exactly without breaking unions into parts. This is useful in libraries and frameworks that rely on precise type behavior.
💼 Career
Understanding advanced TypeScript types like non-distributive conditional types is valuable for frontend and backend developers working with complex type-safe codebases, improving code quality and reducing bugs.
Progress0 / 4 steps
1
Create the generic type IsExactlyString
Create a generic type called IsExactlyString with a type parameter T. Use a conditional type that compares [T] to [string] to avoid distribution. Return true if they are equal, otherwise false.
Typescript
Need a hint?

Wrap the type parameter T and string in tuples to prevent distribution.

2
Create variables to test IsExactlyString
Create three variables: testString with type IsExactlyString, testNumber with type IsExactlyString, and testUnion with type IsExactlyString.
Typescript
Need a hint?

Use the generic type IsExactlyString with the exact types string, number, and string | number.

3
Assign values to variables to check type compatibility
Assign true to testString, and false to both testNumber and testUnion.
Typescript
Need a hint?

Assign the boolean values true or false matching the expected results of the type checks.

4
Print the results to verify the non-distributive conditional type
Use console.log to print the values of testString, testNumber, and testUnion.
Typescript
Need a hint?

Print each variable on its own line using console.log.