arktypea
arktype9mo ago
nidx

functions that take in types

I have certain patterns i would like to make simpler like default arrrays or unique checks but I can't seem to figure out how to type them

this is an example I would like to streamline

type("string[]") // this type is not always the same, can be regex, etc...
    .or("undefined")
    .pipe((v) => v ?? [])
    .narrow(
      (v, ctx) =>
        new Set(v).size === v.length ||
        ctx.mustBe("array with unique elements"),
    )


I was able to write wrapper functions but only if i restrict them to being string[]

const uniqueDefaultStringArrayDef = (schema: Type<string[]>) =>
  defaultEmptyStringArrayDef(uniqueStringArrayDef(schema));

const defaultEmptyStringArrayDef = (schema: Type<string[]>) =>
  schema.or("undefined").pipe((v) => v ?? []);

const uniqueStringArrayDef = (schema: Type<string[]>) =>
  schema.narrow(
    (a, ctx) =>
      new Set(a).size === a.length || ctx.mustBe("array with unique elements"),
  );


is there a better way I can do this that is more generic

I did try this from another post, but it seems to stomp on the type and did not work for narrow

export const defaultArray = <const def>(input: type.validate<def>) =>
  type(input as type.cast<type.infer<def>>)
    .or("undefined")
    .pipe((v) => v ?? []);
Was this page helpful?