Is there support for readonly arrays? #860
-
Typescript has a special type for immutable arrays (excerpt from the official docs) let a: ReadonlyArray<number> = [1, 2, 3];
let b: readonly number[] = [1, 2, 3];
a.push(102); // error
b[0] = 101; // error Is there any support for such type to be expressed in Typebox schemas? Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@thes01 Hi,
Unfortunately, there's not currently a way to infer isolated readonly tuples (i.e. those not embedded in outer types) but Unsafe is a reasonable workaround. The reason has to do with the way TB inference works; where an outer type (TObject, TFunction and TConstructor) will ascribe the This said, following is a ReadonlyTuple type that will perform the isolated readonly inference via Unsafe (if you need a a type to handle this) import { Type, Static, TSchema } from '@sinclair/typebox'
export type TReadonlyTuple<T extends readonly TSchema[], Acc extends readonly unknown[] = []> =
T extends [infer L extends TSchema, ...infer R extends TSchema[]]
? TReadonlyTuple<R, readonly [...Acc, Static<L>]>
: Acc
const ReadonlyTuple = <T extends TSchema[], R = TReadonlyTuple<T>>(types: [...T]) =>
Type.Unsafe<R>(Type.Tuple(types))
const T = ReadonlyTuple([Type.String(), Type.Number()])
type T = Static<typeof T> // readonly [string, number] I intend to revisit this aspect of TypeBox when it drops support for TS 4.x as there is functionality specific to 5.x that may assist here. Initial updates will likely apply specifically to Type.Const (short term) with isolated readonly more broadly implemented in later revisions. Hope this helps |
Beta Was this translation helpful? Give feedback.
@thes01 Hi,
Unfortunately, there's not currently a way to infer isolated readonly tuples (i.e. those not embedded in outer types) but Unsafe is a reasonable workaround. The reason has to do with the way TB inference works; where an outer type (TObject, TFunction and TConstructor) will ascribe the
readonly
modifier to the interior type. As isolated types don't have an outer type, there is nothing to ascribe the modifier.This said, following is a ReadonlyTuple type that will perform the isolated readonly inference via Unsafe (if you need a a type to handle this)
TypeScript Link Here