Typescript widening object properties of Zod enum type to string
See original GitHub issueIf I define enum
and use it in the object, the object property still has the type of the enum
:
enum A { a = "a" }
const a = { a: A.a }
// type of a is { a: A }
However, if I define the same enum using zod, the type of object property is string
and not narrowed to enum anymore.
const A = z.enum(["a"])
const a = { a: A.a }
// type of a is { a: string }
Issue Analytics
- State:
- Created 10 months ago
- Reactions:1
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Generating Zod schema from TS type definitions #53 - GitHub
I'm just beginning to convert a large TS project with many types, ... Zod Object Schema --zod.infer--> TS Types --typescript-json-schema--> ...
Read more >Untitled
I'm using the term "schema" to broadly refer to any data type/structure, from a simple `string` to a complex nested object. Zod is...
Read more >How to extend enums in TypeScript - LogRocket Blog
Extending an enum allows you to essentially copy a variable definition and add something extra to it.
Read more >zod - npm
It's a TypeScript-first schema declaration library with rigorous inferred types, incredible developer experience, and a few killer features ...
Read more >How to Avoid the Infamous "Cannot read properties of ... - Bitovi
With TypeScript, there are two ways of interpreting null and undefined ... because TypeScript is widening the undefined type to string type.
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
Hi @elemti , I wonder if you have usecases where you need to define a schema in-line with an object? (such as below)
I agree its surprising that TS will widen the type to
string
inside an object, I’m curious about that and will look at it… but if you can usez.object()
for the entire object then it will work as expected:@akoltun I took a look at the implementation, and except for the way the enums are stored and checked (an object for nativeEnum and an array for Enum) there’s not that much difference - for compatibility as the README says if I took a guess. Would love for someone more knowledgeable to chime in!
hi @maxArturo , usually I run into this problem when trying to use
.transform()
to enhance an objectI wonder if there’s any better way to enhance / add new keys to an object instead of doing this?