QA
Intermediate LevelJavaScript & TypeScript

How do conditional types (T extends U ? X : Y) work in TypeScript?

❓ Interview Prompt: Explain conditional type evaluation, type-level branching, and distributive conditional types over naked unions.

Conditional types select one of two possible types based on a condition expressed as a type relationship test:

Syntax:

type IsString<T> = T extends string ? true : false;

Distributive Conditional Types:

When conditional types act on a naked generic type parameter T, given a union type, the condition automatically distributes over the union members:

•
IsString<string | number> resolves to IsString<string> | IsString<number> → true | false.

Code Implementation Example

typescript
// Conditional Type definition
type NonNullableType<T> = T extends null | undefined ? never : T;

type CleanString = NonNullableType<string | null | undefined>; // string!

// Filtering union types with distributivity
type ExtractStrings<T> = T extends string ? T : never;

type MixedUnion = 'a' | 42 | 'b' | true;
type OnlyStrings = ExtractStrings<MixedUnion>; // "a" | "b"
💡Conditional type branching and distributive union filtering.
🎯 Interview Key Takeaway

Conditional types perform ternary checks at the type level. Naked generic unions automatically distribute across conditions.

#TypeScript#Conditional Types#Distributivity#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?