![](/img/trans.png)
[英]How do I get typescript to infer the return type of a function based on the return type on a function of its arguments
[英]In TypeScript, how do I make a function's return type based on the return type of one of its arguments?
有什么方法可以让我的函数的返回类型根据其参数之一而有所不同? 例如:
interface Person {
name: string;
job: string;
}
interface Animal {
name: string;
deadly: boolean;
}
function getPerson(): Person {
return {
name: 'Bob',
job: 'Manager',
};
}
function getAnimal(): Animal {
return {
name: 'Spot',
deadly: false,
};
}
function create(generator: () => Person | Animal): ReturnType<typeof generator>[] {
return []
}
const people = create(getPerson);
这是一种密切的,除了类型people
是(Person | Animal)[]
我需要它是Person[]
-换句话说,它可以查看getPerson
参数并知道此函数将返回Person
。 我当然知道我可以重写该函数,所以我可以这样做:
const people = create<Person>(getPerson);
但是我宁愿从争论中以某种方式推断出这一点。
弄清楚了! 我刚刚修改了上面代码的这一部分:
function create<M>(generator: () => M): M[] {
return []
}
const people = create(getPerson);
const animals = create(getAnimal);
那行得通。
您已经弄清楚了,如果您想查找/了解更多信息,我只是想补充一下,该概念称为“泛型”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.