Some small examples of dependent types in TypeScript
Go to file
2022-09-19 10:42:11 -05:00
src Add dependent type demos 2022-09-19 10:25:40 -05:00
.eslintignore Initial commit 2022-09-16 17:34:34 +00:00
.eslintrc.json Initial commit 2022-09-16 17:34:34 +00:00
.gitignore Add dependent type demos 2022-09-19 10:25:40 -05:00
LICENSE Initial commit 2022-09-16 17:34:34 +00:00
package.json Add dependent type demos 2022-09-19 10:25:40 -05:00
pnpm-lock.yaml Add dependent type demos 2022-09-19 10:25:40 -05:00
README.md Update README 2022-09-19 10:42:11 -05:00
tsconfig.json Initial commit 2022-09-16 17:34:34 +00:00

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 of first(...) 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.