A
arktype12mo ago
Micha

How to specify a property of type function?

In Typescript I have defined it like this:
type User = {
accounts: accounts?: (() => Promise<Account>)[];
}
type User = {
accounts: accounts?: (() => Promise<Account>)[];
}
But how to achieve the same in Arktype? PS: Are there any soon plans to extend the Website with more examples? (e.g. the keyword page to explain how they need to be used e.g. Function ) I experience it as quite hard to find answers through the discord search.
6 Replies
ssalbdivad
ssalbdivad12mo ago
Yeah the current docs are awful I apologize for that. Better docs are a top priority for 2.0 especially as things stabilize. You would have to use as Infer for a type like this because there is no way to validate the type of a function at runtime. You'd basically be casting it.
Micha
MichaOP12mo ago
If you say, there is no way to validate the type of a function at runtime, what is Zod doing? https://zod.dev/?id=functions https://zod.dev/?id=promises Or are you talking about the whole function and not from argument and return type validation?
ssalbdivad
ssalbdivad12mo ago
I was working on API like this which I think would be very cool for defining functions with validated input/output
No description
ssalbdivad
ssalbdivad12mo ago
But that's totally different from checking that an arbitrary function that already exists has the expected signature at runtime The only thing you can introspect about a function at runtime is the number of arguments it accepts, and even then that gets messy since ...args aren't included
ssalbdivad
ssalbdivad12mo ago
This is essentially a more concise version of Zod's function API
No description
ssalbdivad
ssalbdivad12mo ago
Although related, when I publish that fn API, it would allow you to define functions that could be introspected at runtime since the types could be attached But if you just think about a scenario like this, it becomes clear why a normal function can't be validated:
const validateNumberToString = (f: (...args: never[]) => unknown) => {
// impossible to implement
}

// valid
validateNumberToString((n: number) => `${n}`)
// invalid
validateNumberToString((n: number) => n === 9801 ? null : "ok")
const validateNumberToString = (f: (...args: never[]) => unknown) => {
// impossible to implement
}

// valid
validateNumberToString((n: number) => `${n}`)
// invalid
validateNumberToString((n: number) => n === 9801 ? null : "ok")
Technically if the function accepts a finite number of input combinations they could be exhaustively tested, but that really would only occur for functions that accept no inputs or have inputs that are unions of literals (and something like that is generally not a problem for runtime validation but rather one for testing via something like fast-check)

Did you find this page helpful?