Is it possible to define something like a general correspondence function by the differentiated type of union? Say we have the following type definitions:
const Kinds = {
A: 'A',
B: 'B',
};
type Kind = typeof Kinds.A | typeof Kinds.B;
type Value = A | B;
interface A {
kind: Kinds.A
}
interface B {
kind: Kinds.B
}
With the switch statement, you can define a matching function, for example:
interface Matcher<T> {
Kinds.A: (value: A) => T
Kinds.B: (value: B) => T
}
function match<T>(matcher: Matcher<T>) {
return function(value: Value) {
switch (value.kind) {
case Kinds.A: return matcher[Kinds.A](value);
case Kinds.B: return matcher[Kinds.B](value);
}
}
}
He does this work, but it is very tedious to define such functions, especially when you have many members of the association.
Is it possible to somehow simplify this definition, perhaps with Mapped Types or other existing tools from the last 2.1 branch.
I played with "Mapped Types", but I'm not sure that you can actually get a specific Value , even when I know Good , for example, something like:
type Matcher<T> = {[P in Kind]: (value: P) => T};
function match<T>(matcher: Matcher<T>) {
return function(value: Value) {
return matcher[value.kind](value);
}
}
P .