|
1 | 1 | # Decoding JSON from Headers, Query Parameters, and URL Parameters |
2 | 2 |
|
3 | | -There are three type parameters to a codec: `t.Type<I, O, A>`. The third parameter |
4 | | -determines the type that the `decode` function receives. Most codecs have the third |
5 | | -parameter set to `unknown`. However, the type for `JsonFromString` in `io-ts-types` is |
6 | | -`t.Type<Json, string, string>`. Therefore, `JsonFromString` expects a string type before |
7 | | -passing it to `decode`. You can easily convert `JsonFromString` to |
8 | | -`t.Type<Json, string, unknown>` using `t.string`. |
| 3 | +Though we know headers, url parameters, and query parameters will be received as a |
| 4 | +`string` or `string[]` value, due to a limitation in api-ts, `httpRequest` only accepts |
| 5 | +codecs that decode values starting from the `unknown` type. Consequently, decoding a |
| 6 | +header, url parameter, or query parameter with a codec like `JsonFromString`, which can |
| 7 | +only decode values typed as `string`, will produce a error like: |
| 8 | + |
| 9 | +``` |
| 10 | +Type 'Type<Json, string, string>' is not assignable to type 'Mixed'. |
| 11 | + Types of property 'validate' are incompatible. |
| 12 | + Type 'Validate<string, Json>' is not assignable to type 'Validate<unknown, any>'. |
| 13 | + Type 'unknown' is not assignable to type 'string'. |
| 14 | +``` |
| 15 | + |
| 16 | +There's a straightforward pattern you can use when you have a value typed as `unknown` |
| 17 | +but need to decode it with a codec that can only decode a narrower type. This pattern is |
| 18 | +called <em>codec chaining</em>: |
| 19 | + |
| 20 | +```typescript |
| 21 | +declare const JsonFromString: t.Type<Json, string, string>; |
| 22 | +declare const t.string: t.Type<string, string, unknown>; |
| 23 | + |
| 24 | +const myCodec: t.Type<Json, string, unknown> = t.string.pipe(JsonFromString); |
| 25 | +``` |
| 26 | + |
| 27 | +Here, `t.string` decodes a value from `unknown` to `string`, and then `JsonFromString` |
| 28 | +decodes the same value from `string` to `Json`. |
9 | 29 |
|
10 | 30 | For example: |
11 | 31 |
|
|
0 commit comments