sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.77k stars 152 forks source link

Tuple with rest items (or Array with prefixedItems) #756

Closed alexey13 closed 6 months ago

alexey13 commented 6 months ago

Good day @sinclairzx81!

Question about tuple with rest items.

type T = ['me', 'you', ...string[]];

Made some research, its possible in json-schema with help of prefixItems and items https://json-schema.org/understanding-json-schema/reference/array#id7 but not possible currently in typebox, right?

Thanks a lot!

sinclairzx81 commented 6 months ago

@alexey13 Hi!

Unfortunately, TypeBox doesn't support this type currently as it's tied to the Draft-7 specification for Tuple representation (which is the default for Ajv). However, you can still implement this type manually....

There's a couple of ways you can approach this. Either using Type.Unsafe (using Ajv as your validator), or registering a new type with the TypeRegistry.


Ajv + Unsafe Type

The following implements this type using Unsafe. To use this type, you will need to configure Ajv for draft 2020-12. This is generally the quickest way to get the type working.

Documentation on configuring Ajv for Draft 2012-12 can be found here

TypeScript Link Here

import { Type, Static, TSchema } from '@sinclair/typebox'

export type TupleRestStatic<T extends TSchema[], Rest extends TSchema, Acc extends unknown[] = []> = 
    T extends [infer L extends TSchema, ...infer R extends TSchema[]]
      ? TupleRestStatic<R, Rest, [...Acc, Static<L>]>
      : [...Acc, ...Static<Rest>[]]

export const TupleRest = <T extends TSchema[], Rest extends TSchema>(items: [...T], rest: Rest) => 
  Type.Unsafe<TupleRestStatic<T, Rest>>({
    type: 'array',
    prefixItems: items,
    unevaluatedItems: rest
  })

const T = TupleRest([Type.String(), Type.Number()], Type.Boolean())

type T = Static<typeof T> // [string, number, ...boolean[]]

TypeRegistry

The following implements the same type using the TypeBox TypeRegistry. This approach will require you to manually implement the check logic for the type.

import { Type, Static, TSchema, TypeRegistry, Kind } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'

// --------------------------------------------------------------------
// TupleRest
// --------------------------------------------------------------------
TypeRegistry.Set<TTupleRest>('TupleRest', (schema, value) => {
  return (
    Array.isArray(value) && value.length >= schema.prefixItems.length &&
    schema.prefixItems.every((schema, index) => Value.Check(schema, value[index])) &&
    value.every((value, index) => index < schema.prefixItems.length || Value.Check(schema.unevaluatedItems, value))
  )
})
export type TupleRestStatic<T extends TSchema[], Rest extends TSchema, Acc extends unknown[] = []> = 
    T extends [infer L extends TSchema, ...infer R extends TSchema[]]
      ? TupleRestStatic<R, Rest, [...Acc, Static<L>]>
      : [...Acc, ...Static<Rest>[]]

export interface TTupleRest<T extends TSchema[] = [], Rest extends TSchema = TSchema> extends TSchema {
  [Kind]: 'TupleRest'
  static: TupleRestStatic<T, Rest>
  type: 'array'
  prefixItems: T
  unevaluatedItems: Rest
}
export function TupleRest<T extends TSchema[], Rest extends TSchema>(prefixItems: [...T], unevaluatedItems: Rest): TTupleRest<T, Rest> {
  return { [Kind]: 'TupleRest', type: 'array', prefixItems, unevaluatedItems } as never
}

// ... 

const T = TupleRest([Type.String(), Type.Number()], Type.Boolean())

type T = Static<typeof T> // [string, number, ...boolean[]]

const R = Value.Check(T, ['', 1, true, true, true]) // true

I'll make a note to implement an overload for the Rest parameter on Type.Tuple once TypeBox transitions over to Draft 2020-12. But for now, the above approach is the current best option for representing this type.

Let me know if this helps Cheers S

alexey13 commented 6 months ago

Thank you very much! Will use TypeRegistry example, its awesome!