3
3
import * as t from 'io-ts' ;
4
4
5
5
/**
6
- * Creates a default value for an io-ts codec. This is useful
7
- *
6
+ * Creates a default value for an io-ts codec.
8
7
* @param codec - the codec whose default we want to create
9
8
* @returns an object honoring the io-ts codec
10
- *
11
9
* @example Use Case: CSV Generation from Typed Objects
12
10
* Consider the following codec:
13
- *
11
+ *
14
12
* const UserCodec = t.intersection([
15
13
* t.type({
16
14
* id: t.string,
@@ -22,23 +20,22 @@ import * as t from 'io-ts';
22
20
* ])
23
21
*
24
22
* Suppose we want to generate a CSV file from the objects below with UserCodec type:
25
- *
23
+ *
26
24
* const users = [
27
25
* { id: '1', name: 'Alice', email: 'alice@email .com' },
28
26
* { id: '2', name: 'Bob' },
29
27
* ]
30
- *
28
+ *
31
29
* To generate a CSV, we need a consistent set of columns (headers) that includes
32
30
* ALL possible fields, even if some objects don't have all properties. In the example
33
31
* above, though, notice that the second user does not have the email property.
34
- *
32
+ *
35
33
* In such a case, createDefaultCodec(UserCodec) is useful to construct an object
36
34
* with all possible fields, which can then be used to generate the complete CSV header:
37
35
* "id,name,email".
38
- *
36
+ *
39
37
* The example above is pretty simple, but things get very compliated the more complex
40
38
* is the codec. In any case, createDefaultCodec is useful for outputting the expected CSV header.
41
- *
42
39
*/
43
40
export const createDefaultCodec = < C extends t . Mixed > (
44
41
codec : C ,
0 commit comments