Skip to main content

Type Gymnastics

Type programming:

LevelEnvironmentOperandsOperations
Program levelRuntimeValuesFunctions
Type levelCompile timeSpecific typesGeneric types
TypeScript TermSet Term
never (Empty set)
Literal typeSingle element set
Value assignable to TValue ∈ T (Member)
T1 assignable to T2T1 ⊆ T2 (Subset)
T1 extends T2T1 ⊆ T2 (Subset)
T1 | T2T1 ∪ T2 (Union)
T1 & T2T1 ∩ T2 (Intersection)
unknownUniversal set

Types

Examples

  • PathOf<Form> complex recursive types.
  • Type-safe React router advanced types.
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