У меня возникли некоторые проблемы при объединении типов защиты 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/