A
arktype•4mo ago
errata

template literal/backtick string types e.g. type T = `type-${string}`

I can't see how to do in Ark:
type UserId = `user-${string}`
type UserId = `user-${string}`
I specifically want compile-time checking. Tried to drop it in "1:1" style, but this doesn't work as-is:
const UserId = type('`user-${string}`') // doesn't work
const UserId = type('`user-${string}`') // doesn't work
nor did it work trying to use 'type' as a tagged template:
const UserId = type`user-${type('string')}`
const UserId = type`user-${type('string')}`
I did look in the docs but I don't believe it's there yet, and if it's in the tests I didn't spot it Do I have to set it up as a custom string constraint so it'd be like const UserId = type('string-userId')? IIUC this doesn't get the compile-time checking:
// Subtypes like 'email' are inferred like 'string' but provide additional validation at runtime. email: "string.email",
8 Replies
TizzySaurus
TizzySaurus•4mo ago
Ig this is what you're referring to: https://github.com/arktypeio/arktype/issues/491
GitHub
Template literal · Issue #491 · arktypeio/arktype
Would allow the equivalent TS syntax: // inferred as a${string}z[] const t = type("a${string}z[]") Internally should probably compile to a regex.
TizzySaurus
TizzySaurus•4mo ago
You'd need to use a morph/narrow for now (probably a narrow)
const UserId = type("string").narrow(s => s.startsWith("user-"))
const UserId = type("string").narrow(s => s.startsWith("user-"))
or whatever Although the inferred type would just be string
errata
errataOP•4mo ago
Yeah even if it didn't give me the exact template type I'd still be happy so long as it's a tagged/branded/opaque type that forced the string through a type predicate before use
errata
errataOP•4mo ago
errata
errataOP•4mo ago
hm, this won't work consistently either:
export const UserId = type("string").narrow(s => s.startsWith("user-"))
export type UserId = `type-${string}`
export const UserId = type("string").narrow(s => s.startsWith("user-"))
export type UserId = `type-${string}`
I wonder if ark should allow you to supply/override the type you want it to infer as e.g. something like
const UserId = type<`user-${string}`>("string").narrow(s => s.startsWith("user-"))
const UserId = type<`user-${string}`>("string").narrow(s => s.startsWith("user-"))
ssalbdivad
ssalbdivad•4mo ago
const t = type(/^user-/).as<`user-${string}`>
const t = type(/^user-/).as<`user-${string}`>
errata
errataOP•4mo ago
whoo perfect thank you
PIat
PIat•4mo ago
Ohhh yeahhhhh RegEx 🤩
Want results from more Discord servers?
Add your server