0
0
Typescriptprogramming~7 mins

Non-distributive conditional types in Typescript

Choose your learning style9 modes available
Introduction

Sometimes you want to check a type without splitting it into parts. Non-distributive conditional types help you do that.

You want to test a whole type at once, not each part separately.
You have a union type but want to treat it as one piece.
You want to avoid automatic splitting of union types in conditions.
You want to write safer type checks that don't change behavior unexpectedly.
Syntax
Typescript
type NonDistributive<T> = [T] extends [SomeType] ? TrueType : FalseType;

Wrapping the type T in square brackets [T] stops TypeScript from splitting unions.

This way, the condition checks the whole type, not each union member separately.

Examples
This is a normal conditional type. It splits unions and checks each part.
Typescript
type IsString<T> = T extends string ? true : false;

// For union type
// IsString<'a' | number> becomes true | false (distributive)
Wrapping T in brackets stops splitting. It checks the whole union at once.
Typescript
type IsStringNonDist<T> = [T] extends [string] ? true : false;

// For union type
// IsStringNonDist<'a' | number> becomes false (non-distributive)
Sample Program

This program shows the difference between distributive and non-distributive conditional types. The first splits the union and returns a union of results. The second checks the whole union at once and returns a single result.

Typescript
type IsString<T> = T extends string ? true : false;
type IsStringNonDist<T> = [T] extends [string] ? true : false;

// Test with union

// Distributive conditional type
type Test1 = IsString<'hello' | 42>; // true | false

// Non-distributive conditional type
type Test2 = IsStringNonDist<'hello' | 42>; // false

// To see results, we create variables with these types

const test1a: Test1 = true;
const test1b: Test1 = false;

// const test2a: Test2 = true; // Error: Type 'true' is not assignable to type 'false'
const test2b: Test2 = false;

console.log('Test1 can be true or false:', test1a, test1b);
console.log('Test2 is always false:', test2b);
OutputSuccess
Important Notes

Non-distributive conditional types are useful when you want to avoid unexpected splitting of union types.

Remember to wrap the type parameter in square brackets to make the condition non-distributive.

Summary

Conditional types normally split unions into parts and check each part.

Wrapping the type in square brackets stops this splitting, making the check non-distributive.

This helps when you want to test the whole type as one piece.