如何创建函数返回泛型类型,它从联合类型扩展而来



这是我的例子,我不知道如何实现功能"MakeCoffee"请帮助。谢谢。

interface Latte {
ouncesEspresso: number;
milkToEspresso: 4;
};

interface Cappuccino = {
ouncesEspresso: number;
milkToEspresso: 2;
};
interface IceLatte extends Latte {
icePortion: "light" | "normal" | "extra";
}
type Coffee = Latte | Cappuccino;
function MakeCoffee<T extends Coffee>(): T {
// I don't know how to figure out which type is used in that union type
// is this possible? if not, how to change the design
}

根据我的经验,使用不绑定到任何函数参数的泛型参数是一种不好的做法。有些情况下你需要这样做,但这不是关于你的情况。

如果你只是想让生成器函数,试试这个:

interface Latte {
ouncesEspresso: number;
milkToEspresso: 4;
};
interface Cappuccino {
ouncesEspresso: number;
milkToEspresso: 2;
};
const coffeeKind = <
MilkCount extends 4 | 2
>(coffee: Coffee, milkCount: MilkCount):
coffee is Extract<Coffee, { milkToEspresso: MilkCount }> =>
coffee.milkToEspresso === milkCount
interface IceLatte extends Latte {
icePortion: "light" | "normal" | "extra";
}
type Coffee = Latte | Cappuccino;
function makeCoffee(milkToEspresso: 4, ouncesEspresso: number): Latte
function makeCoffee(milkToEspresso: 2, ouncesEspresso: number): Cappuccino
function makeCoffee(milkToEspresso: Coffee['milkToEspresso'], ouncesEspresso: number) {
return {
milkToEspresso,
ouncesEspresso,
}
}
const cappuccino = makeCoffee(2, 4) // Cappuccino
const latte = makeCoffee(4, 4) // Latte

输入链接描述

看到function-overloads

相关内容

  • 没有找到相关文章

最新更新