【发布时间】:2021-03-02 10:51:29
【问题描述】:
假设我有类似的架构:
type GetDog = () => { animal: string; bark: boolean };
const getDog: GetDog = () => ({ animal: 'dog', bark: true });
type GetCat = () => { animal: string; meow: boolean };
const getCat: GetCat = () => ({ animal: 'cat', meow: true });
type AnimalFactory =
| ((callback: GetDog) => ReturnType<typeof getDog>)
| ((callback: GetCat) => ReturnType<typeof getCat>);
const calmAnimalFactory: AnimalFactory = (callback) => {
// Some fancy stuff
return callback();
};
calmAnimalFactory 作为参数应该接受getDog 函数或getCat 函数,然后返回相应的值。问题是我猜类型推断不像我想象的那样工作。 calmAnimalFactory 内部的回调不会推断GetDog | GetCat 的类型,而是any。我认为 Typescript 应该确定 calmAnimalFactory 的类型,而 calmAnimalFactory(getDog) 应该输入为
((callback: GetDog) => ReturnType<typeof getDog>)
而calmAnimalFactory(getCat) 应输入为
((callback: GetCat) => ReturnType<typeof getCat>)
我希望有可能实现,但我不知道为什么它不能那样工作。
【问题讨论】:
标签: typescript typescript-typings