diff --git a/README.md b/README.md index 035e255..fe2dc00 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,29 @@ -# template-npm-typescript +# TypeScript Dependent Types -A template repository for NPM packages built with Typescript and PNPM. \ No newline at end of file +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: + +```ts +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: + +```ts +type PiOrTau = 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.