我正在向一个API端点发送请求,它的响应根据响应中名为productType
的字段而有所不同.例如,API可以返回如下响应:
// response 1
{
productType: 'Product1',
product: 'Some product information'
}
// response 2
{
productType: 'Product2',
product: {moreNestedFields: 'Some product information'}
}
我希望能够根据productType
在我的客户端代码中运行不同的逻辑(缩小类型).
以下是我这样做的简化try :
type Product = 'Product1' | 'Product2';
type MyResponse<TProduct extends Product> = {
product: TProduct extends 'Product1' ? 'SomeType' : 'SomeOtherType';
productType: TProduct;
};
function getResponse<T extends Product>() {
// This is accually some fetch request
return {} as MyResponse<T>;
}
const response = getResponse();
if (response.productType === 'Product1') {
// myProduct is not type narrowed?
// I am expecting it to only have 'SomeType' but its type is <'SomeType' | 'SomeOtherType'>
const myProduct = response.product;
// do something with myProduct
} else {
// ..
}
我遗漏了什么?我怎样才能做到这一点呢?