arktypea
arktype10mo ago
francis

New v2.1 arktype matcher: is there a way to match on string literal values?

An example from the docs:
type Data =
    | {
            id: 1
            oneValue: number
      }
    | {
            id: 2
            twoValue: string
      }
const discriminateValue = match
    // .in allows you to specify the input TypeScript allows for your matcher
    .in<Data>()
    // .at allows you to specify a key at which your input will be matched
    .at("id")
    .match({
        1: o => `${o.oneValue}!`,
        2: o => o.twoValue.length,
        default: "assert"
    })


If I try to switch this to a typical string-value based discriminated union, I get an error:
type Data =
  | {
      id: "one";
      oneValue: number;
    }
  | {
      id: "two";
      twoValue: string;
    };
const discriminateValue = match
  // .in allows you to specify the input TypeScript allows for your matcher
  .in<Data>()
  // .at allows you to specify a key at which your input will be matched
  .at("id")
  .match({
    one: (o) => `${o.oneValue}!`,
    two: (o) => o.twoValue.length,
    default: "assert",
  });


'one is unresolvable' and 'two is unresolvable'
Was this page helpful?