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

Using a unit type instead of a variant? #971

Open
jawnothin opened this issue Dec 10, 2024 · 3 comments
Open

Using a unit type instead of a variant? #971

jawnothin opened this issue Dec 10, 2024 · 3 comments
Assignees
Labels
question Further information is requested

Comments

@jawnothin
Copy link

Is there a way to make use of a unit type instead of having to re-type it out as a picklist?

type Choices = 'a' | 'b' | 'c'

v.picklist<Choices>()

instead of having to do

v.picklist(['a', 'b', 'c'])
@fabian-hiller
Copy link
Owner

No, this would require a compiler to translate your TypeScript type into run-time code. TypeScript types do not exist at runtime and are removed before the transpiled JavaScript code is executed. However, you can retrieve the TypeScript type from the runtime code. Here is an example:

import * as v from 'valibot';

const options = ['a', 'b', 'c'] as const;
type Choices = typeof options[number];
const Schema = v.picklist(options);

@fabian-hiller fabian-hiller self-assigned this Dec 11, 2024
@fabian-hiller fabian-hiller added the question Further information is requested label Dec 11, 2024
@jawnothin
Copy link
Author

Right I figured that would be the case.

The problems lies in the package that generates this list in the first place, as it doesn't generate the array of strings, but just the unit type instead.

Thanks for the reply.

@fabian-hiller
Copy link
Owner

If your main concern is a mismatch between the generated type and the schema, you could use the satisfies keyword:

import * as v from 'valibot';

type Choices = 'a' | 'b' | 'c';
const Schema = v.picklist(['a', 'b', 'c']) satisfies v.GenericSchema<Choices>;

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

No branches or pull requests

2 participants