A
arktype•7d ago
Genshii

"Custom" type or equivalent to valibot.custom()?

I might just be missing something obvious, but I want to do something like this:
import type { SomeType } from "some-external-library"

const foo = type({
foo: "string",
bar: "SomeType"
})
import type { SomeType } from "some-external-library"

const foo = type({
foo: "string",
bar: "SomeType"
})
Obviously SomeType isn't a valid value, so I could do something like this:
const foo = type({
foo: "string",
bar: "unknown" as type.cast<SomeType>
})
const foo = type({
foo: "string",
bar: "unknown" as type.cast<SomeType>
})
But I have a feeling that's not the right way to do it. Is there something like valibot's custom?
5 Replies
ssalbdivad
ssalbdivad•7d ago
You can use narrow for arbitrary validation logic + if you add a type predicate like : data is SomeType it will be inferred as the output So you'd start with whatever you can validate directly with other constraints, then add custom logic on top of that needed If you can express everything you need without a custom function but just want to cast the type, you can use type(...).as<SomeType>()
Genshii
GenshiiOP•6d ago
Ahh okay, thanks Sorta related, when creating a type for an object that has functions on it, I was doing this:
type MyFuncType = (foo: string) => void

const foo = type({
foo: "Function" as type.cast<MyFuncType>,
})
type MyFuncType = (foo: string) => void

const foo = type({
foo: "Function" as type.cast<MyFuncType>,
})
If I want to avoid casting I suppose I should do this?
const foo2 = type({
foo: type("Function").narrow((myFunc): myFunc is MyFuncType => typeof myFunc === "function"),
})
const foo2 = type({
foo: type("Function").narrow((myFunc): myFunc is MyFuncType => typeof myFunc === "function"),
})
Althought I guess that's kinda redundant because I'm assuming that's what the Function keyword does anyway
ssalbdivad
ssalbdivad•6d ago
Yeah, also a type predicate is equivalent to casting so there is no difference in terms of safety
Genshii
GenshiiOP•6d ago
makes sense, ty
ssalbdivad
ssalbdivad•6d ago
You could use type("Function").as<MyFuncType>() also I suppose, all roads lead to Rome haha (with equal amounts of type-unsafety required since it's impossible to validate functions at runtime 😅)

Did you find this page helpful?