[BUG] [typescript-fetch] Generated code not compatible with typescript flag "exactOptionalPropertyTypes"
Bug Report Checklist
- [X] Have you provided a full/minimal spec to reproduce the issue?
- [X] Have you validated the input using an OpenAPI validator (example)?
- [ ] Have you tested with the latest master to confirm the issue still exists?
- [X] Have you searched for related issues/PRs?
- [X] What's the actual output vs expected output?
- [ ] [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
Typescript has various flags, some of which help you to write code many of which add more type-safety. One of which is the option exactOptionalPropertyTypes which, if enabled, ensures that properties of an object, if optional, are not allowed to get assigned undefined unless it's explicitly stated in their type-definition.
The generator typescript-fetch generates code which is incompatible with this flag, that means, if an object property is defined as optional with the type null | string, the value undefined is assigned to it. When this flag is enabled, the types should either be changed to undefined | null | string or the assignment should be changed to set the value to null instead.
openapi-generator version
v6.4.0
OpenAPI declaration file content or url
{
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "6.4.0",
"generators": {
"v2.0": {
"generatorName": "typescript-fetch",
"inputSpec": "./swagger.json",
"output": "./generated/api"
}
}
}
}
Generation Details
The problem occurs for any swagger file, because even the basic infrastructure provided by the generator generates code not compliant with this rule.
I've also found it sometimes generating invalid code for types within type-definitions. A sample of which can be found by using the following swagger.json file: https://gist.github.com/SimonSimCity/350234540ab5363a7bef7244842cfb57
Steps to reproduce
Related issues/PRs
None found.
Suggest a fix
Because the usage of the flag exactOptionalPropertyTypes is recommended (see: https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes) this generator should IMO comply with this rule.
I use this at my project :(
type GetOptional<T> = {
[K in keyof T as T[K] extends Required<T>[K] ? never : K]: T[K]
}
type Optional<T> = Omit<T, keyof GetOptional<T>> & {
[K in keyof GetOptional<T>]: T[K] | undefined
}
type TransformPaths<T> = T extends object
? Optional<{
[K in keyof T]: TransformPaths<T[K]>
}>
: T
type TransformedPaths = TransformPaths<paths>
export const fetchClient = createClient<TransformedPaths>({})
You can also use this from type-fest: https://github.com/sindresorhus/type-fest/blob/main/source/undefined-on-partial-deep.d.ts