arktypea
arktype16mo ago
francis

Is there a recommended way to transform a type union into a discriminated union by adding a tag?

I'm not sure I'm describing this well, but I have a situation with two types that I am .or-ing together.

It all works, but I'm interacting with a library that needs a discriminated union to function properly for type narrowing, and I am not sure how to add a discriminated union tag based on which type in the Or resolved (if that makes sense?)

Here's a simple example to demonstrate:
const first = type({ key: "string" });
const second = type({ key: "number" });
const combined = first.or(second);


I'd like to have this be resolve to e.g. { key: string, tag: 'first' } | { key: number, tag: 'second' } based on which branch in the union was followed.

I've tried it with this:
const first = type({ key: "string" }).pipe((o) => ({ ...o, _tag: "first" }) as const);
const second = type({ key: "number" }).pipe((o) => ({ ...o, _tag: "second" }) as const);
const combined = first.or(second);


and it works - but seems inelegant. Is there a more idiomatic solution?
Was this page helpful?