Skip to content

Is it possible to type string literals using Valibot/v.pipe? #620

Answered by fabian-hiller
zaydek asked this question in Q&A
Discussion options

You must be logged in to vote

Yes, this is possible but only when using custom or transform:

import * as v from 'valibot';

export const GlobalShopifyProductID = v.custom<`gid://shopify/Product/${string}`>(
  (input) => typeof input === 'string' && input.startsWith('gid://shopify/Product/')
);

type GlobalShopifyProductIDType = v.InferOutput<typeof GlobalShopifyProductID>;
//   ^ type GlobalShopifyProductIDType = `gid://shopify/Product/${string}`
import * as v from 'valibot';

export const GlobalShopifyProductID = v.pipe(
  v.string(),
  v.startsWith('gid://shopify/Product/'),
  v.transform((input) => input as `gid://shopify/Product/${string}`)
);

type GlobalShopifyProductIDType = v.InferOutput<typeof GlobalShopifyPr…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@zaydek
Comment options

Answer selected by fabian-hiller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants