Skip to content
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

Type error when using S.literal and S.optional with default #2002

Closed
mrmckeb opened this issue Jan 29, 2024 · 2 comments · Fixed by #2005 or #2000
Closed

Type error when using S.literal and S.optional with default #2002

mrmckeb opened this issue Jan 29, 2024 · 2 comments · Fixed by #2005 or #2000
Labels
bug Something isn't working schema

Comments

@mrmckeb
Copy link

mrmckeb commented Jan 29, 2024

What version of Effect is running?

2.2.2

What steps can reproduce the bug?

When migrating from S.optional(...).withDefault(...), we hit an issue with S.literal. This hasn't been an issue for us with any other types.

This example code block throws a type error on the default property.

const FooSchema = S.literal('a', 'b', 'c');

const MySchema = S.struct({
  foo: S.optional(FooSchema, {
    default: () => 'a',
    // Object literal may only specify known properties, and
    // 'default' does not exist in type '{ readonly as: "Option"; }'.
  }),
});

The full error is:

No overload matches this call.
  The last overload gave the following error.
    Object literal may only specify known properties, and 'default' does not exist in type '{ readonly as: "Option"; }'.ts(2769)

We can work around the issue by setting the types as below:

const FooSchema = S.literal('a', 'b', 'c');
type Foo = S.Schema.To<typeof AstCacheSchema>;

const MySchema = S.struct({
  foo: S.optional<never, Foo, Foo>(FooSchema, {
    default: () => 'a',
  }),
});

What is the expected behavior?

When using S.literal with S.optional, as: "Option" should not be automatically applied.

What do you see instead?

The error shows that as: "Option" is being automatically applied.

Additional information

TypeScript 5.3.3.

@mrmckeb mrmckeb added the bug Something isn't working label Jan 29, 2024
@gcanti
Copy link
Contributor

gcanti commented Jan 29, 2024

TypeScript errors are a bit cryptic when it comes to overloads (the overload with as: "Option" is only the last one attempted by the type checker), here the actual problem is the default parameter being inferred as string instead of "a", to resolve this you can add as const:

-default: () => "a"
+default: () => "a" as const

@mrmckeb
Copy link
Author

mrmckeb commented Jan 29, 2024

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working schema
Projects
Archived in project
2 participants