are custom (function) types possible? #529
-
ProblemSometimes custom types (type casts) are easier to work: // 1. Need to define pattern to enforce camelCase but it's also a template literal string
const T = Type.String({
pattern: "^(?:[a-z0-9]+(?:[A-Z][a-z0-9]+)*)\\.lintRule[A-Z][a-zA-Z0-9]*$",
}) as unknown as TTemplateLiteral<[TLiteral<`${string}.lintRule${string}`>]>,
// 2. Typing functions is complex and validation not required
const T = Type.Object({
type: Type.Literal("MessageLintRule"),
defaultLevel: Type.String(),
message: Type.Function()
}) QuestionAre custom (function) types possible? // 1. Need to define pattern to enforce camelCase but it's also a template literal string
const T = Type.String<`${string}.lintRule${string}`>({
pattern: "^(?:[a-z0-9]+(?:[A-Z][a-z0-9]+)*)\\.lintRule[A-Z][a-zA-Z0-9]*$",
})
// 2. Typing functions is complex and validation not required
const T = Type.Object({
type: Type.Literal("MessageLintRule"),
defaultLevel: Type.String(),
message: Type.Function<(args: { path: string } => string) >()
}) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 12 replies
-
TypeBox supports Function and Constructor types, but they are not very useful for validation (as JavaScript provides no specification or metadata to check a functions arguments or return types). Rather TypeBox includes them for use in interface definitions (think IDL) for describing callable interface methods (see this project for an example of their usage) const Add = Type.Function([Type.Number(), Type.Number()], Type.Number()])
type Add = Static<typeof Add> // type Add = (arg0: number, arg1: number) => number With regards to their construction, it's not possible to construct Functions using TypeScript syntax alone (as TS will erase types on compilation), so the following won't work. const T = Type.Function<(a: number, b: number) => number>() // types are erased on compile But you can use Type.Unsafe which will infer as any type you give it...however you will lose the metadata to describe the function (which may be ok depending on your usecase). Information on using Unsafe can be found here const T = Type.Unsafe<(a: number, b: number) => number>({ ... }) Hope this helps! |
Beta Was this translation helpful? Give feedback.
Would the following work?