[英]In TypeScript, how do I make a function's return type based on the return type of one of its arguments?
Is there some way I can have a function whose return type varies based on one of its arguments? 有什么方法可以让我的函数的返回类型根据其参数之一而有所不同? For example:
例如:
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);
This is kind of close, except the type of people
is (Person | Animal)[]
. 这是一种密切的,除了类型
people
是(Person | Animal)[]
I need it to be Person[]
- in other words, it can look at the getPerson
argument and know that this function will return a Person
. 我需要它是
Person[]
-换句话说,它可以查看getPerson
参数并知道此函数将返回Person
。 I realize, of course, I could rewrite the function so I can do this: 我当然知道我可以重写该函数,所以我可以这样做:
const people = create<Person>(getPerson);
But I'd rather have it infer this from the arguments somehow. 但是我宁愿从争论中以某种方式推断出这一点。
Figured it out! 弄清楚了! I just modified this part of the above code:
我刚刚修改了上面代码的这一部分:
function create<M>(generator: () => M): M[] {
return []
}
const people = create(getPerson);
const animals = create(getAnimal);
And that worked. 那行得通。
您已经弄清楚了,如果您想查找/了解更多信息,我只是想补充一下,该概念称为“泛型”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.