![](/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.