Skip to content

Commit 21225ed

Browse files
GabrielCastrodomoritz
authored andcommitted
Fix not being able to get default types when using type assertions (YousefED#196)
* Fix not being able to get default types when using type assertions * fix schema typo
1 parent 45e61da commit 21225ed

File tree

4 files changed

+77
-1
lines changed

4 files changed

+77
-1
lines changed
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
type Foo = "a" | "b" | "c" | boolean | number;
2+
3+
class MyObject {
4+
varBoolean: Foo = <any> false;
5+
varInteger: Foo = <any> 123;
6+
varString: Foo = <any> "123";
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-06/schema#",
3+
"properties": {
4+
"varBoolean": {
5+
"anyOf": [
6+
{
7+
"enum": [
8+
"a",
9+
"b",
10+
"c",
11+
false,
12+
true
13+
]
14+
},
15+
{
16+
"type": "number"
17+
}
18+
],
19+
"default": false
20+
},
21+
"varInteger": {
22+
"anyOf": [
23+
{
24+
"enum": [
25+
"a",
26+
"b",
27+
"c",
28+
false,
29+
true
30+
]
31+
},
32+
{
33+
"type": "number"
34+
}
35+
],
36+
"default": 123
37+
},
38+
"varString": {
39+
"anyOf": [
40+
{
41+
"enum": [
42+
"a",
43+
"b",
44+
"c",
45+
false,
46+
true
47+
]
48+
},
49+
{
50+
"type": "number"
51+
}
52+
],
53+
"default": "123"
54+
}
55+
},
56+
"required": [
57+
"varBoolean",
58+
"varInteger",
59+
"varString"
60+
],
61+
"type": "object"
62+
}

test/schema.test.ts

+2
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ describe("schema", () => {
195195

196196
assertSchema("ignored-required", "MyObject");
197197

198+
assertSchema("default-properties", "MyObject");
199+
198200
// not supported yet #116
199201
// assertSchema("interface-extra-props", "MyObject");
200202

typescript-json-schema.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,12 @@ export class JsonSchemaGenerator {
362362
// try to get default value
363363
let valDecl = prop.valueDeclaration as ts.VariableDeclaration;
364364
if (valDecl && valDecl.initializer) {
365-
const initial = valDecl.initializer;
365+
let initial = valDecl.initializer;
366+
367+
while (ts.isTypeAssertion(initial)) {
368+
initial = initial.expression;
369+
}
370+
366371
if ((<any>initial).expression) { // node
367372
console.warn("initializer is expression for property " + propertyName);
368373
} else if ((<any>initial).kind && (<any>initial).kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {

0 commit comments

Comments
 (0)