Repository navigation
Expand file tree
/
Copy pathtypes.ts
More file actions
69 lines (62 loc) 路 1.39 KB
/
Copy pathtypes.ts
File metadata and controls
69 lines (62 loc) 路 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { type InputOf, type OutputOf, type Type, identity } from "./type";
/**
* A number type to be used with `option`
*
* Throws an error when the provided string is not a number
*/
export const number: Type<string, number> = {
async from(str) {
const decoded = Number.parseFloat(str);
if (Number.isNaN(decoded)) {
throw new Error("Not a number");
}
return decoded;
},
displayName: "number",
description: "a number",
};
/**
* A string type to be used with `option`.
*/
export const string: Type<string, string> = {
...identity(),
description: "a string",
displayName: "str",
};
/**
* A boolean type to be used with `flag`.
*/
export const boolean: Type<boolean, boolean> = {
...identity(),
description: "a boolean",
displayName: "true/false",
defaultValue() {
return false;
},
};
/**
* Makes any type optional, by defaulting to `undefined`.
*/
export function optional<T extends Type<any, any>>(
t: T,
): Type<InputOf<T>, OutputOf<T> | undefined> {
return {
...t,
defaultValue(): OutputOf<T> | undefined {
return undefined;
},
};
}
/**
* Transforms any type into an array, useful for `multioption` and `multiflag`.
*/
export function array<T extends Type<any, any>>(
t: T,
): Type<InputOf<T>[], OutputOf<T>[]> {
return {
...t,
async from(inputs: InputOf<T>[]): Promise<OutputOf<T>[]> {
return Promise.all(inputs.map((input) => t.from(input)));
},
};
}