I have a union type of two types with similar fields, some of different types. I want to have a function take a name (name being a common field) and return the type of another field (value). Right now, it's returning the union of all types of value. If I supply A or B to test with test<A>(), it locks what the string name can be to the function, but I want to provide a string name and get the type out of it. Is that possible?
interface A {
name: "A";
value: number;
}
interface B {
name: "B";
value: string;
}
type AB = A | B;
const arr: AB[] = [
{name: "A", value: 1},
{name: "A", value: 2},
{name: "B", value: "asd"}
];
function test<T extends AB>(name: T["name"]): T["value"] {
return arr.find(t => t.name === name)!.value;
}
const asd = test("A");