gpt4 book ai didi

TypeScript 条件类型和类型保护

转载 作者:行者123 更新时间:2023-12-03 16:58:50 25 4
gpt4 key购买 nike

我在结合 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/

最佳答案

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

关于TypeScript 条件类型和类型保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53504227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com