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:
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:
and it works - but seems inelegant. Is there a more idiomatic solution?
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:
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:
and it works - but seems inelegant. Is there a more idiomatic solution?