Some small examples of dependent types in TypeScript
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Garrett Mills 082417cb33
Update README
2 years ago
src Add dependent type demos 2 years ago
.eslintignore Initial commit 2 years ago
.eslintrc.json Initial commit 2 years ago
.gitignore Add dependent type demos 2 years ago
LICENSE Initial commit 2 years ago
README.md Update README 2 years ago
package.json Add dependent type demos 2 years ago
pnpm-lock.yaml Add dependent type demos 2 years ago
tsconfig.json Initial commit 2 years ago

README.md

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.