Skip to content

Commit df730aa

Browse files
committed
feat(swagger-ts): support nullable types
1 parent d93668e commit df730aa

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

packages/swagger-ts/src/generators/TypeGenerator.test.ts

+28
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,34 @@ describe('TypeGenerator simple', () => {
9595
)
9696
})
9797

98+
test('generate type for nullable fields', async () => {
99+
const generator = new TypeGenerator({
100+
withJSDocs: false,
101+
resolveName: ({name}) => name,
102+
enumType: 'asConst',
103+
dateType: 'string',
104+
optionalType: 'questionToken',
105+
})
106+
107+
const schema: OpenAPIV3.SchemaObject = {
108+
type: 'object',
109+
properties: {
110+
foo: {
111+
type: 'string',
112+
nullable: true
113+
}
114+
}
115+
}
116+
117+
const node = generator.build({schema, baseName: 'Test'})
118+
const output = print(node, undefined)
119+
expect(await format(output)).toMatch(await format(`
120+
export type Test = {
121+
foo?: string | null
122+
}
123+
`))
124+
})
125+
98126
test('generate type for Pets', async () => {
99127
const oas = await oasPathParser(path)
100128
const generator = new TypeGenerator({

packages/swagger-ts/src/generators/TypeGenerator.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,11 @@ export class TypeGenerator extends SchemaGenerator<Options, OpenAPIV3.SchemaObje
108108
return null
109109
}
110110

111-
if (schema) {
111+
if (schema.nullable) {
112+
return createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] })
113+
} else {
112114
return type
113115
}
114-
115-
return createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] })
116116
}
117117

118118
/**

0 commit comments

Comments
 (0)