Check out this example of Typescript code utilizing a generic to narrow down a second parameter's possible input value based on the first value:
type DataMap = {
A: { a: string };
B: { b: string };
};
type Type = keyof DataMap;
type Data<TType extends Type> = DataMap[TType];
interface ItemOptions<TType extends Type> {
data: Data<TType>;
type: TType;
}
function Item<TType extends Type>({ type, data }: ItemOptions<TType>) {
if (type === "A") {
// Typescript error: Property 'a' does not exist on type '{ a: string; } | { b: string; }'.
return data.a;
}
if (type === "B") {
// Typescript error: Property 'b' does not exist on type '{ a: string; } | { b: string; }'.
return data.b;
}
}
I'm puzzled as to why this code doesn't compile, considering that it correctly identifies valid parameter values when calling the function:
// This works
Item({ type: "B", data: { b: "" } });
// These don't compile
Item({ type: "B", data: { a: "" } });
Item({ type: "A", data: { b: "" } });
What could be the reason for this issue, and what would be a reliable way to resolve it?