forked from vega/ts-json-schema-generator
/
UnionType.ts
60 lines (51 loc) · 1.73 KB
/
UnionType.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
import { BaseType } from "./BaseType";
import { uniqueTypeArray } from "../Utils/uniqueTypeArray";
import { NeverType } from "./NeverType";
import { derefType } from "../Utils/derefType";
export class UnionType extends BaseType {
private readonly types: BaseType[];
private discriminator?: string = undefined;
public constructor(types: readonly BaseType[]) {
super();
this.types = uniqueTypeArray(
types.reduce((flatTypes, type) => {
if (type instanceof UnionType) {
flatTypes.push(...type.getTypes());
} else if (!(type instanceof NeverType)) {
flatTypes.push(type);
}
return flatTypes;
}, [] as BaseType[])
);
}
public setDiscriminator(discriminator: string) {
this.discriminator = discriminator;
}
public getDiscriminator() {
return this.discriminator;
}
public getId(): string {
return `(${this.types.map((type) => type.getId()).join("|")})`;
}
public getName(): string {
return `(${this.types.map((type) => type.getName()).join("|")})`;
}
public getTypes(): BaseType[] {
return this.types;
}
public normalize(): BaseType {
if (this.types.length === 0) {
return new NeverType();
} else if (this.types.length === 1) {
return this.types[0];
} else {
const union = new UnionType(this.types.filter((type) => !(derefType(type) instanceof NeverType)));
if (union.getTypes().length > 1) {
return union;
} else {
return union.normalize();
}
// return this;
}
}
}