I'm trying to write a function that will perform a particular calculation based on the passed key and parameters. I also want to enforce a relationship between the passed key and parameters, so I have used a generic function with a constraint:
interface ProductMap {
one: {
basePrice: number;
discount: number;
},
two: {
basePrice: number;
addOnPrice: number;
}
}
function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
switch (key) {
case 'one': {
return params.basePrice - params.discount; // Property 'discount' does not exist on type 'ProductMap[K]'.
}
case 'two': {
return params.basePrice + params.addOnPrice;
}
}
}
Maybe I'm thinking about this in the wrong way, but it seems like typescript should be able to narrow the generic type in the switch statement. The only way I could get it to work was with this awkwardness:
function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
switch (key) {
case 'one': {
const p = params as ProductMap['one'];
return p.basePrice - p.discount;
}
case 'two': {
const p = params as ProductMap['two'];
return p.basePrice + p.addOnPrice;
}
}
}
Can anyone explain why #1 won't work or offer an alternative solution?