Typescript Conditional Types: Use extends, infer, and keyof to create conditional logic in types.
TypeScript's Conditional Types provide a way to perform type-level computations using a ternary-like syntax.
By combining extends
, infer
, and keyof
, we can express complex type logic. Here's a breakdown:
1. Basic Conditional Types Syntax typescript
If
T
is assignable toU
, the type resolves toX
; otherwise, it resolves toY
.
2. Using extends in Conditional Types
You can check if one type extends another:
3. Using infer to Extract Types
infer
allows you to extract types in conditional types, often within generic contexts like functions or arrays.
Example: Extract Return Type of a Function
Example: Extract Array Element Type
4. Using keyof with Conditional Types
keyof
extracts the keys of a type, useful when working with object types.
Example: Conditional Type to Check for a Specific Property
5. Combining extends, infer, and keyof
You can combine all three to create powerful type utilities.
Example: Extract the Type of a Specific Property
Example: Deeply Nested Return Type Extraction
Summary
By combining extends
, infer
, and keyof
in TypeScript conditional types:
extends
checks subtype relations.infer
extracts and infers types.keyof
works with keys of object types.
These tools enable you to build highly flexible, type-safe utilities for complex type manipulations.