// 不用 @ts-ignore 不用函数重载方式 能行吗?
interface IFish {
swim(): number;
}
interface IBird {
fly(): string;
}
type FishOrBirdOrNever<T> = T extends IFish
? ReturnType<typeof fish.swim> :
T extends IBird
? ReturnType<typeof bird.fly>
: undefined;
function isFish(pet: IFish | IBird): pet is IFish {
return (pet as IFish).swim !== undefined;
}
function isBird(pet: IFish | IBird): pet is IBird {
return (pet as IBird).fly !== undefined;
}
function getPetAction<T extends IFish | IBird>(pet: T): FishOrBirdOrNever<T> {
const result = isFish(pet) ? pet.swim() : isBird(pet) ? pet.fly() : undefined;
// 不用 @ts-ignore 不用函数重载
return result; // 报错 这是为什么 (不用上面两种方式 又要怎么解决呢)
/*
* Type 'string | number' is not assignable to type 'FishOrBirdOrNever<T>'.
* Type 'string' is not assignable to type 'FishOrBirdOrNever<T>'.
*/
}
const fish: IFish = {
swim() {
return 100;
}
};
const bird: IBird = {
fly() {
return "Can't fly";
}
};
const p1 = getPetAction(fish); // 根据参数推断类型
const p2 = getPetAction(bird);
console.log(p1);
console.log(p2);
https://codepen.io/pantao/pen...
只是给出一个可行的编写方案,单纯看上面楼主的代码,感觉 TypeScript 的使用方法应该不太对吧。