sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
5.04k stars 159 forks source link

Variadic Any Typed function parameters #931

Open eddie-atkinson opened 3 months ago

eddie-atkinson commented 3 months ago

Hi there,

First of all huge thanks for creating this library. I am in awe of how many thorny cases you've considered and covered whilst maintaining a user friendly but principled interface.

I am attempting to represent a logging interface using Typebox and am running into some issues with variadic parameters:


export interface Logger {
  info: (...args: any[]) => void;
  warn: (...args: any[]) => void;
  error: (...args: any[]) => void;
  debug: (...args: any[]) => void;
}

The suggestion from the Typebox workbench is something like this:

const LoggerSchema = Type.Object({
  info: Type.Function([...Type.Rest(Type.Array(Type.Any()))], Type.Void()),
  warn: Type.Function([...Type.Rest(Type.Array(Type.Any()))], Type.Void()),
  error: Type.Function([...Type.Rest(Type.Array(Type.Any()))], Type.Void()),
  debug: Type.Function([...Type.Rest(Type.Array(Type.Any()))], Type.Void()),
});
export type Logger = Static<typeof LoggerSchema>;

However that type resolves to something like:

image

Which isn't quite right

sinclairzx81 commented 3 months ago

@eddie-atkinson Hi,

Function rest parameters are not currently supported in TypeBox, but are being considered in later revisions. Currently the Type.Rest function only extracts variadic types from Intersect, Union, Tuple structures and returns the interior TSchema[] (which isn't a type).

There are intentions to repurpose Rest for your exact use case, and have been prototyping this feature somewhat recently, however this would be a breaking change as it involves promoting the Rest function result as an actual type that can be remapped on functions and constructors. The eventual API for this will look as follows.

const F = Type.Function([Type.Rest(Type.String())], Type.Void())

type F = Static<typeof F> // type F = (...arg: string[]) => void

Note, I don't expect this to be ready for some time, but will be aiming for a significant revision near the end of the year. Have marked this issue as future for the time being.

Hope this brings some insight S

eddie-atkinson commented 3 months ago

Hi @sinclairzx81,

Many thanks for taking the time to respond, I always appreciate the depth of your answers - it makes for excellent documentation.

Looking forward to seeing this feature supported at some point, best of luck with the next version