Conditional Types
Conditional Types — the core idea
A conditional type uses the form T extends U ? X : Y. TypeScript selects a branch while analyzing types. This is not the JavaScript ternary operator; it creates neither a runtime test nor an emitted branch.
What you’ll learn
- Explain conditional types with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: Because string extends string, Description<string> resolves to the literal type "text". Number does not extend string, so the second type is "other". JavaScript prints the two strings that were assigned.
Keep the boundary clear: Do not assume conditional types change a value dynamically. Use a runtime typeof check when the actual value determines behavior.
See the idea as a flow
Run the complete TypeScript example
Save the code as conditional-types.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type Description<T> = T extends string ? "text" : "other";
const a: Description<string> = "text";
const b: Description<number> = "other";
console.log(a);
console.log(b);Verified output
text
otherBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable conditional-types.ts; run: node conditional-types.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
Because string extends string, Description<string> resolves to the literal type "text". Number does not extend string, so the second type is "other". JavaScript prints the two strings that were assigned.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Do not assume conditional types change a value dynamically. Use a runtime typeof check when the actual value determines behavior.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Define IsArray<T> using T extends readonly unknown[] and test it with string[] and string.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
A conditional type uses the form T extends U ? X : Y.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.