arktype icon indicating copy to clipboard operation
arktype copied to clipboard

Support static config for custom error codes

Open ssalbdivad opened this issue 7 months ago • 0 comments

I had implemented part of this in beta but am delaying it until a future release.

Here's some random context from what I had implemented:

export type ArkErrorContextsByCode = extend<
  {
    [kind in ArkErrorCode]: Declaration<kind>["errorContext"];
  },
  StaticArkOption<"errors">
>;

declare global {
  export interface StaticArkConfig {
    preserve(): never;
    errors(): {};
  }
}

tests:

import { attest } from "@arktype/attest";
import type { DerivableErrorContext } from "@arktype/schema";
import { type } from "arktype";

interface SpecialErrorContext extends DerivableErrorContext {
  reversesTo: string;
}

declare global {
  export interface StaticArkConfig {
    errors(): {
      nonPalindrome: SpecialErrorContext;
    };
  }
}

describe("errors", () => {
  it("custom static", () => {
    const palindrome = type("string", ":", (s, ctx) =>
      s === [...s].reverse().join("")
        ? true
        : ctx.falsify("nonPalindrome", {
            reversesTo: [...s].reverse().join(""),
          })
    );
  });
  it("infers context parameter", () => {
    attest(() =>
      type("string", ":", (s, ctx) =>
        ctx.falsify("nonPalindrome", {
          // @ts-expect-error
          reversesTo: [...s].reverse(),
        })
      )
    ).type.errors("Type 'string[]' is not assignable to type 'string'");
  });
});

ssalbdivad avatar Jan 12 '24 16:01 ssalbdivad