Skip to content

enum type inference loses refinement #1066

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

Closed
alpha0010 opened this issue Apr 4, 2022 · 3 comments
Closed

enum type inference loses refinement #1066

alpha0010 opened this issue Apr 4, 2022 · 3 comments

Comments

@alpha0010
Copy link

Using a zod enum in an object degenerates to generic string.

const MyEnumType = z.enum(['a', 'b']);
type MyEnum = z.infer<typeof MyEnumType>;
type MyObject = {foo: MyEnum};

function testFunc() {
  let x: MyObject = {foo: 'a'};
  const parsed = MyEnumType.safeParse('a');
  if (parsed.success) {
    let y = {foo: parsed.data};
    x = y; // Type '{ foo: string; }' is not assignable to type 'MyObject'.
  }
}

As a workaround, I can use z.union([z.literal('a'), z.literal('b')]), but the verbosity is inconvenient.

@colinhacks
Copy link
Owner

Seems to be a weird quirk of TypeScript, not a Zod bug. Try this as a workaround:

const y = { foo: parsed.data } as const;

@alpha0010
Copy link
Author

Thanks, I will try that. In case it is useful for the future, the io-ts way seems to work.

import * as t from 'io-ts';

const MyEnumType = t.keyof({a: null, b: null});
type MyEnum = t.TypeOf<typeof MyEnumType>;
type MyObject = {foo: MyEnum};

function testFunc() {
  let x: MyObject = {foo: 'a'};
  const data: unknown = 'a';
  if (MyEnumType.is(data)) {
    let y = {foo: data};
    x = y; // Works.
  }
}

@alpha0010
Copy link
Author

Potentially related microsoft/TypeScript#36579.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants