typescript - TypeScript 条件类型和类型保护
问题描述
我在结合 TypeScript 的类型保护和条件类型时遇到了一些问题。考虑:
export interface IThisThing {
someProp: number;
}
export function isIThisThing(type: any): type is IThisThing {
return !!type.someProp;
}
export interface IThatThing {
someOtherProp: string;
}
export function isIThatThing(type: any): type is IThatThing {
return !!type.someOtherProp;
}
function doAThing<T extends IThisThing | IThatThing>(
data: T
): T extends IThisThing ? IThisThing : IThatThing {
if (isIThisThing(data)) {
return data; // Type 'T & IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
};
return data; // Type 'T' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
// Type 'IThisThing | IThatThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
// Type 'IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
}
我希望该doAThing
函数接受IThisThing
或IThatThing
返回与它接收到的相同类型。唉,编译器因以下消息而窒息:
Type 'T & IThisThing' is not assignable to type 'T extends IThisThing ? IThisThing : IThatThing'.
有人可以让我直截了当吗?我觉得我已经很接近了,但还没有完全正确。我在这篇博文中使用了第一个示例(看起来非常相似):http: //artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/
解决方案
Typescript 不会让您将任何内容分配给仍然具有自由类型参数的条件类型,它只是不受支持。您最好的选择是使用泛型和条件类型的签名以及返回两种可能性的联合的更简单的实现签名
export interface IThisThing {
someProp: number;
}
export function isIThisThing(type: any): type is IThisThing {
return !!type.someProp;
}
export interface IThatThing {
someOtherProp: string;
}
export function isIThatThing(type: any): type is IThatThing {
return !!type.someOtherProp;
}
function doAThing<T extends IThisThing | IThatThing>(
data: T
): T extends IThisThing ? IThisThing : IThatThing
function doAThing(
data: IThisThing | IThatThing
): IThisThing | IThatThing {
if (isIThisThing(data)) {
return data;
};
return data;
}
推荐阅读
- reactjs - React-google-maps 状态更新导致 infoWindow 进入无限循环渲染
- hyperledger-fabric - 在“编写您的第一个应用程序”官方部分调用“invoke.js”失败
- android - 转义色度键颜色
- python - 在networkx中加速随机最小生成树?
- android - 在片段android导航抽屉中显示对话框
- python - 重塑 pandas DataFrame Python 3.x
- google-sheets - 带变量查询
- postgresql - 如何从 postgres 中的多边形值中找到该区域?
- django - OperationalError at /admin/ no such table: IEL_user 浏览管理员时
- uitableview - 如何删除 TVOS 中的默认分隔符空间