Imagine a scenario where there is a concept of a union type called Thing
, which combines types Foo
, Bar
, and Baz
, each identified by the property tag
.
interface Foo {
tag: 'Foo'
foo: string
}
interface Bar {
tag: 'Bar'
bar: number
}
interface Baz {
tag: 'Baz'
baz: boolean
}
type Union = Foo | Bar | Baz
Now, the goal is to create a mapped type that iterates over the tags within the Union
, associating each tag with its corresponding interface type. The main question at hand is: Can we access a type from a union based on its tag value?
interface Tagged {
tag: string
}
type TypeToFunc<U extends Tagged> = {
// Is it possible to retrieve the type for the given tag from the union type?
// What should replace the ??? in this case?
readonly [T in U['tag']]: (x: ???) => string
}
const typeToFunc: TypeToFunc<Union> = {
// x must be of type Foo
Foo: x => `FOO: ${x.foo}`,
// x must be of type Bar
Bar: x => `BAR: ${x.bar}`,
// x must be of type Baz
Baz: x => `BAZ: ${x.baz}`,
}
If this approach is not feasible, are there other methods to achieve such mapping between types?