Joh*_*lly 6 types conditional-statements 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'.
}
Run Code Online (Sandbox Code Playgroud)
我希望该doAThing函数接受IThisThingorIThatThing并返回与接收到的类型相同的类型。唉,编译器因以下消息而窒息:
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;
}
Run Code Online (Sandbox Code Playgroud)