首页 > 解决方案 > 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函数接受IThisThingIThatThing返回与它接收到的相同类型。唉,编译器因以下消息而窒息:

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/

标签: typescripttypesconditional

解决方案


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;
}

推荐阅读