.optional() and --exactOptionalPropertyTypes
See original GitHub issueCurrently, .optional() behaves like:
const user = z.object({
username: z.string().optional(),
});
type C = z.infer<typeof C>; // { username?: string | undefined };
This results in a type mismatch when you’re using --exactOptionalPropertyTypes in TypeScript 4.4 and expecting type C
to match an interface definition like:
interface User {
username?: string;
}
.partial(), .partialBy(), .deepPartial() all have the same issue.
It would be nice to unbundle the optionality of the key from the union type with undefined for the value.
I suggest that these methods be changed to specify the optional absence of the key by default, and perhaps accept an option to restore the old behavior of adding .or(z.undefined())
to the value schema(s). This would unfortunately be a breaking change, but it makes more sense than the current behavior, especially as more projects adopt --exactOptionalPropertyTypes.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:18
- Comments:13 (1 by maintainers)
Top Results From Across the Web
TSConfig Option: exactOptionalPropertyTypes - TypeScript
exactOptionalPropertyTypes makes TypeScript truly enforce the definition provided as an optional property: ts. const settings = getUserSettings ();.
Read more >`exactOptionalPropertyTypes: true` breaks type checking of ...
This tsconfig rule breaks typechecking of optional values since the ... Semantically it makes more sense for optional() to follow this ...
Read more >optional vs. undefined - TkDodo's blog
Since Version 4.4, TypeScript has a compiler option called exactOptionalPropertyTypes that can help us distinguish a bit better between the two ...
Read more >In TypeScript, is there a difference between optional ...
but such optional parameters/fields are also allowed to be present ... toUpperCase() : "undefined"); } function takeOpt(v: Opt) { const x ...
Read more >Announcing TypeScript 4.4 - Microsoft Developer Blogs
That let us access string methods like toUpperCase() without getting an ... Exact Optional Property Types ( --exactOptionalPropertyTypes ).
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I don’t think this issue should be considered stale. It is a real issue that multiple users of the library are facing.
I don’t think this should be closed due to staleness. This issue is currently blocking me from adopting
--exactOptionalPropertyTypes
and from the recent activity it looks like there are multiple users interested in a solution.