Skip to content

Commit ff65f81

Browse files
committed
add support for disjoint union types (fix #27)
1 parent d03bddc commit ff65f81

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/index.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { join, parse, ParsedPath, resolve } from 'path'
77

88
enum RuleType {
99
'Any', 'TypedArray', 'Enum', 'AllOf', 'AnyOf', 'Reference', 'NamedSchema', 'AnonymousSchema',
10-
'String', 'Number', 'Void', 'Object', 'Array', 'Boolean', 'Literal'
10+
'String', 'Number', 'Void', 'Object', 'Array', 'Boolean', 'Literal', 'Union'
1111
}
1212

1313
enum EnumType {
@@ -87,6 +87,9 @@ class Compiler {
8787
case 'object': return RuleType.Object
8888
case 'string': return RuleType.String
8989
}
90+
if (Array.isArray(rule.type)) {
91+
return RuleType.Union
92+
}
9093
if (this.isNumberLiteral(rule)) {
9194
return RuleType.Number
9295
}
@@ -238,6 +241,8 @@ class Compiler {
238241
return new TsType.Union(rule.anyOf!.map(_ => this.toTsType(_)))
239242
case RuleType.Reference:
240243
return this.resolveType(rule.$ref!, propName!)
244+
case RuleType.Union:
245+
return new TsType.Union((rule.type as any[]).map(_ => this.toTsType(_)))
241246
}
242247
throw new Error('Unknown rule:' + rule.toString())
243248
}

test/cases/disjoint-type.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
export var schema = {
2+
"title": "Example Schema",
3+
"description": "My cool schema",
4+
"type": "object",
5+
"properties": {
6+
"value": {
7+
"type": ["number", "string"]
8+
},
9+
"anotherValue": {
10+
"type": ["null", "string"]
11+
}
12+
},
13+
"required": ["value"]
14+
}
15+
16+
export var types = `/** My cool schema */
17+
export interface ExampleSchema {
18+
value: number | string;
19+
anotherValue?: null | string;
20+
[k: string]: any;
21+
}`

0 commit comments

Comments
 (0)