generated from garrettmills/template-npm-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.
30 lines
1.3 KiB
30 lines
1.3 KiB
# 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:
|
|
|
|
```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'|'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.
|