-
Notifications
You must be signed in to change notification settings - Fork 400
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Option for adding undefined
to optional union for optional properties.
#604
Comments
Could you share an example of a JSON schema and the output it produces today, and how exactly that might cause issues for users? |
No problem. Given the schema, {
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0
}
},
"additionalProperties": false,
"required": ["firstName"]
} the library currently produces the following output: export interface ExampleSchema {
firstName: string;
age?: number;
} Let's say we have a function, function testFunction(data: ExampleSchema) { /* ... */ } Calling that function with testFunction({
firstName: "John",
age: undefined
});
/*
Argument of type '{ firstName: string; age: undefined; }' is not assignable to parameter of type 'ExampleSchema' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
Types of property 'age' are incompatible.
Type 'undefined' is not assignable to type 'number'.
*/ The solution in the above is to simply omit the property altogether, but if the value of age is coming from another possibly undefined variable, things get messier: const age: number | undefined = undefined;
testFunction({
firstName: "John",
...(age ? { age: age } : {})
}); Our code may internally equate the non-existence of an optional type with the existence a value of Thusly I propose a new option in The following would be the output of the above schema with this flag enabled: export interface ExampleSchema {
firstName: string;
age?: number | undefined;
} testFunction({
firstName: "John",
age: undefined // Ok
}); |
Gotcha. That sounds reasonable to me. I think the more explicit |
In TypeScript, when
exactOptionalPropertyTypes
is set to true, properties that areoptional?:
but not do not include| undefined
in their union can not be assigned a value of undefined.For generating code that will be consumed by others, we may not want to force them to turn off
exactOptionalPropertyTypes
. For that please consider an option to includeundefined
in generated type unions of non-required properties.The text was updated successfully, but these errors were encountered: