Some small examples of dependent types in TypeScript
| src | ||
| .eslintignore | ||
| .eslintrc.json | ||
| .gitignore | ||
| LICENSE | ||
| package.json | ||
| pnpm-lock.yaml | ||
| README.md | ||
| tsconfig.json | ||
TypeScript Dependent Types
Some examples of type-dependent and value-dependent types in TypeScript.
The nicest way to interact with these examples is to open this repo in an editor with TypeScript
support so you can hover your cursor over a term to view its computed type. Failing that, you can
compile the examples using pnpm build.
Many TypeScript values can be lifted as specific types. For example:
const value = {pi: 3.14}
type ValueType1 = {pi: 3.14}
type ValueType2 = typeof value
Here, value has the literal type ValueType1, which can be captured by the definition of ValueType2.
We can make use of this fact to make TypeScript type definitions dependent on specific values:
type PiOrTau<Num extends 'pi'|'tau'> = Num extends 'pi' ? {pi: 3.14} : {tau: 6.28}
This repo includes a few examples using this technique:
first.ts- the simplest example, an implementation offirst(...)that fails type-checking when applied to empty arrays.overloading.ts- a more interesting example that uses type inference to determine the signature and return type of a function.routes.ts- a more complex example, a webserver route definition library that supports parameter middleware.- The signature of the route handler function is dependent on the types of any parameter middleware defined on the route.