/
typescript.ts
69 lines (65 loc) 路 1.7 KB
/
typescript.ts
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 { genString } from "./string";
import { genObjectKey, wrapInDelimiters } from "./utils";
export type TypeObject = {
[key: string]: string | TypeObject;
};
export interface GenInterfaceOptions {
extends?: string | string[];
export?: boolean;
}
export const genTypeObject = (object: TypeObject, indent = ""): string => {
const newIndent = indent + " ";
return wrapInDelimiters(
Object.entries(object).map(([key, value]) => {
const [, k = key, optional = ""] =
key.match(/^(.*[^?])(\?)?$/) /* c8 ignore next */ || [];
if (typeof value === "string") {
return `${newIndent}${genObjectKey(k)}${optional}: ${value}`;
}
return `${newIndent}${genObjectKey(k)}${optional}: ${genTypeObject(
value,
newIndent,
)}`;
}),
indent,
"{}",
false,
);
};
export const genInterface = (
name: string,
contents?: TypeObject,
options: GenInterfaceOptions = {},
) => {
const result = [
options.export && "export",
`interface ${name}`,
options.extends &&
`extends ${
Array.isArray(options.extends)
? options.extends.join(", ")
: options.extends
}`,
contents ? genTypeObject(contents) : "{}",
]
.filter(Boolean)
.join(" ");
return result;
};
export const genAugmentation = (
specifier: string,
interfaces?: Record<
string,
TypeObject | [TypeObject, Omit<GenInterfaceOptions, "export">]
>,
) => {
return `declare module ${genString(specifier)} ${wrapInDelimiters(
Object.entries(interfaces || {}).map(
([key, entry]) =>
" " +
(Array.isArray(entry)
? genInterface(key, ...entry)
: genInterface(key, entry)),
),
)}`;
};