我正在尝试编写一个函数,根据传递的键和参数执行特定的计算。我还想强制传递的键和参数之间的关系,因此我使用了带有约束的通用函数:
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;
}
}
}
也许我对此考虑得不够全面,但似乎Typescript应该能够在switch语句中缩小泛型类型范围。唯一使它发挥作用的方法是采用这种笨拙的方式:
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;
}
}
}
有人能解释一下为什么 #1 不起作用或者提供一个替代方案吗?