【发布时间】:2021-03-24 03:51:58
【问题描述】:
type Bird = { fly: () => "fly" };
type Insect = { annoy: () => "annoy" };
type Dog = { beTheBest: () => "dogdogdog" };
type Animal = Bird | Insect | Dog;
const isBird = (animal: Animal): animal is Bird => {
if ("fly" in animal) return true;
return false;
};
const isInsect = (animal: Animal): animal is Insect => {
if ("annoy" in animal) return true;
return false;
};
const hasWings = (animal: Animal) => {
if (isBird(animal)) return true;
if (isInsect(animal)) return true;
return false;
};
我将两个基本类型保护功能组合到复合 hasWings 保护中,但 TypeScript 并没有推断出它的类型保护特性 - 它只是将 typeof hasWings 推断为 (a: Animal) => boolean。有没有办法可以帮助 TS 推断或明确告诉 hasWings 是 isInsect 和 isBird 类型保护的组合,而无需手动重新指定标准?
// Something like this would be useful to me:
const hasWings = (animal: Animal): ReturnType<typeof isBird> & ReturnType<typeof isInsect> => {
if (isBird(animal)) return true;
if (isInsect(animal)) return true;
return false;
};
// Having to specify the whole list manually is not useful to me:
const hasWings = (animal: Animal): animal is Insect | Bird => {
if (isBird(animal)) return true;
if (isInsect(animal)) return true;
return false;
};
【问题讨论】:
标签: typescript typeguards