0
# Primitive Codecs
1
2
Built-in codecs for basic JavaScript/TypeScript types with runtime validation.
3
4
## Capabilities
5
6
### String Codec
7
8
Validates that a value is a string.
9
10
```typescript { .api }
11
/**
12
* String codec that validates string values
13
*/
14
const string: StringC;
15
16
interface StringC extends Type<string, string, unknown> {}
17
```
18
19
**Usage Example:**
20
21
```typescript
22
import * as t from "io-ts";
23
24
const result = t.string.decode("hello");
25
// result: Right("hello")
26
27
const invalid = t.string.decode(42);
28
// result: Left([validation error])
29
```
30
31
### Number Codec
32
33
Validates that a value is a number (excluding NaN).
34
35
```typescript { .api }
36
/**
37
* Number codec that validates number values
38
*/
39
const number: NumberC;
40
41
interface NumberC extends Type<number, number, unknown> {}
42
```
43
44
**Usage Example:**
45
46
```typescript
47
import * as t from "io-ts";
48
49
const result = t.number.decode(42);
50
// result: Right(42)
51
52
const invalid = t.number.decode("42");
53
// result: Left([validation error])
54
```
55
56
### Boolean Codec
57
58
Validates that a value is a boolean.
59
60
```typescript { .api }
61
/**
62
* Boolean codec that validates boolean values
63
*/
64
const boolean: BooleanC;
65
66
interface BooleanC extends Type<boolean, boolean, unknown> {}
67
```
68
69
### BigInt Codec
70
71
Validates that a value is a bigint.
72
73
```typescript { .api }
74
/**
75
* BigInt codec that validates bigint values
76
*/
77
const bigint: BigIntC;
78
79
interface BigIntC extends Type<bigint, bigint, unknown> {}
80
```
81
82
### Null and Undefined Codecs
83
84
Codecs for null and undefined values.
85
86
```typescript { .api }
87
/**
88
* Null codec that validates null values
89
*/
90
const nullType: NullC;
91
const null: NullC; // exported alias
92
93
interface NullC extends Type<null, null, unknown> {}
94
95
/**
96
* Undefined codec that validates undefined values
97
*/
98
const undefined: UndefinedC;
99
100
interface UndefinedC extends Type<undefined, undefined, unknown> {}
101
102
/**
103
* Void codec that validates void/undefined values
104
*/
105
const voidType: VoidC;
106
const void: VoidC; // exported alias
107
108
interface VoidC extends Type<void, void, unknown> {}
109
```
110
111
### Universal Codecs
112
113
Codecs that handle any or no values.
114
115
```typescript { .api }
116
/**
117
* Unknown codec that accepts any value
118
*/
119
const unknown: UnknownC;
120
121
interface UnknownC extends Type<unknown, unknown, unknown> {}
122
123
/**
124
* Any codec that accepts any value (deprecated, use unknown)
125
*/
126
const any: AnyC;
127
128
interface AnyC extends Type<any, any, unknown> {}
129
130
/**
131
* Never codec that always fails validation
132
*/
133
const never: NeverC;
134
135
interface NeverC extends Type<never, never, unknown> {}
136
```
137
138
### Function Codec
139
140
Validates that a value is a function.
141
142
```typescript { .api }
143
/**
144
* Function codec that validates function values
145
*/
146
const Function: FunctionC;
147
148
interface FunctionC extends Type<Function, Function, unknown> {}
149
```
150
151
### Array and Record Codecs
152
153
Generic container codecs for arrays and objects.
154
155
```typescript { .api }
156
/**
157
* Unknown array codec that validates arrays of unknown elements
158
*/
159
const UnknownArray: UnknownArrayC;
160
161
interface UnknownArrayC extends Type<Array<unknown>, Array<unknown>, unknown> {}
162
163
/**
164
* Unknown record codec that validates objects with string keys and unknown values
165
*/
166
const UnknownRecord: UnknownRecordC;
167
168
interface UnknownRecordC extends Type<{ [key: string]: unknown }, { [key: string]: unknown }, unknown> {}
169
```
170
171
**Usage Examples:**
172
173
```typescript
174
import * as t from "io-ts";
175
176
// Array validation
177
const arrayResult = t.UnknownArray.decode([1, 2, "hello"]);
178
// result: Right([1, 2, "hello"])
179
180
// Record validation
181
const recordResult = t.UnknownRecord.decode({ a: 1, b: "hello" });
182
// result: Right({ a: 1, b: "hello" })
183
```
184
185
### Special Integer Codec
186
187
Branded integer codec for validating integer numbers.
188
189
```typescript { .api }
190
/**
191
* Integer codec that validates integer numbers (branded number)
192
*/
193
const Int: BrandC<NumberC, IntBrand>;
194
195
interface IntBrand {
196
readonly Int: unique symbol;
197
}
198
199
type Int = Branded<number, IntBrand>;
200
```
201
202
**Usage Example:**
203
204
```typescript
205
import * as t from "io-ts";
206
207
const result = t.Int.decode(42);
208
// result: Right(42) with Int brand
209
210
const invalid = t.Int.decode(42.5);
211
// result: Left([validation error - not an integer])
212
```
213
214
## Deprecated Primitives
215
216
These primitives are maintained for backward compatibility but should be avoided in new code:
217
218
```typescript { .api }
219
/**
220
* @deprecated Use UnknownArray instead
221
*/
222
const Array: UnknownArrayC;
223
224
/**
225
* @deprecated Use UnknownRecord instead
226
*/
227
const Dictionary: UnknownRecordC;
228
229
/**
230
* @deprecated Use UnknownRecord instead
231
*/
232
const object: ObjectC;
233
234
/**
235
* @deprecated Use unknown instead
236
*/
237
type mixed = unknown;
238
```
239
240
## Usage Patterns
241
242
### Basic Validation
243
244
```typescript
245
import * as t from "io-ts";
246
import { PathReporter } from "io-ts/PathReporter";
247
248
const validatePrimitives = (data: unknown[]) => {
249
data.forEach((item, index) => {
250
console.log(`Item ${index}:`, item);
251
252
// Test against different primitive codecs
253
const tests = [
254
{ codec: t.string, name: 'string' },
255
{ codec: t.number, name: 'number' },
256
{ codec: t.boolean, name: 'boolean' },
257
{ codec: t.unknown, name: 'unknown' }
258
];
259
260
tests.forEach(({ codec, name }) => {
261
const result = codec.decode(item);
262
if (result._tag === 'Right') {
263
console.log(` ✓ Valid ${name}`);
264
} else {
265
console.log(` ✗ Invalid ${name}:`, PathReporter.failure(result.left));
266
}
267
});
268
});
269
};
270
271
validatePrimitives([42, "hello", true, null, undefined]);
272
```
273
274
### Type Guards
275
276
```typescript
277
import * as t from "io-ts";
278
279
// Use built-in type guards
280
const value: unknown = "hello";
281
282
if (t.string.is(value)) {
283
// value is now typed as string
284
console.log(value.toUpperCase());
285
}
286
287
if (t.number.is(value)) {
288
// This block won't execute
289
console.log(value.toFixed(2));
290
}
291
```
292
293
### Combining Primitives
294
295
```typescript
296
import * as t from "io-ts";
297
298
// Create a union of primitives
299
const StringOrNumber = t.union([t.string, t.number]);
300
301
const result1 = StringOrNumber.decode("hello");
302
// result: Right("hello")
303
304
const result2 = StringOrNumber.decode(42);
305
// result: Right(42)
306
307
const result3 = StringOrNumber.decode(true);
308
// result: Left([validation error])
309
```