Type Gymnastics
| Level | Environment | Operands | Operations |
|---|---|---|---|
| Program level | Runtime | Values | Functions |
| Type level | Compile time | Specific types | Generic types |
TypeScript Term | Set Term |
|---|---|
never | ∅ (Empty set) |
| Literal type | Single element set |
Value assignable to T | Value ∈ T (Member) |
T1 assignable to T2 | T1 ⊆ T2 (Subset) |
T1 extends T2 | T1 ⊆ T2 (Subset) |
T1 | T2 | T1 ∪ T2 (Union) |
T1 & T2 | T1 ∩ T2 (Intersection) |
unknown | Universal set |
Types
- Template literal types.
- Index signature.
- Mapped types.
- Conditional types:
inferinference types....rest types:Items extends [infer Head, ...infer Tail].- Recursive types.
Examples
type PathSegments<Path extends string>
= Path extends `${infer SegmentA}/${infer SegmentB}`
? ParamOnly<SegmentA> | PathSegments<SegmentB>
: ParamOnly<Path>
type ParamOnly<Segment extends string> = Segment extends `:${infer Param}`
? Param
: never
type RouteParams<Path extends string> = {
[Key in PathSegments<Path>]: string
}
interface RouteProps<Path extends string> {
path: Path
render: (routeProps: { match: { params: RouteParams<Path> } }) => void
}
export default function App() {
return (
<Route
path="/user/:username"
render={(routeProps) => {
const params = routeProps.match.params
}}
/>
)
}
References
- Type challenges.
- Type gymnastics.
- Type trident.