gpt4 book ai didi

具有通用联合约束的 TypeScript 函数返回值

转载 作者:行者123 更新时间:2023-12-03 08:31:20 24 4
gpt4 key购买 nike

我无法理解如何在 TypesScript 中实现泛型。我知道有很多类似的问题,但似乎没有一个能解决我的用例。 (有 this question ,但我有一个不同的担忧,即函数的输出与函数的输入是相同的类型)

我想要一个这样的函数,其中泛型仅限于两种不同的类型,并且输出与输入的类型相同:

const increase = <T extends string | number>(
param: T,
): T => {
if (typeof param === "number") {
// Here typescript should know that param can only be a number
return param + 1;
}
// Here TypeScript should know that param can only be a string
return "one more " + param;
};

const stringResult = increase("apple"); // "one more apple"
// Here TypeScript should know that stringResult is a string

const numResult = increase(2); // 3
// Here TypeScript should know that numResult is a number

但是,这会产生如下错误:

Type 'number' is not assignable to type 'T'.
'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.

但我在上面的 if 语句中进行了类型检查,确保 T 应该是 number 而不是 string |数字

我想要的东西可以在 TypeScript 中实现吗?如果是这样,我做错了什么?

最佳答案

如果您不需要该函数成为箭头函数,您可以轻松重载该函数:

function increase(param: string): string;

function increase(param: number): number;

function increase(param: string | number): string | number {
if (typeof param === "number") {
// Here typescript should know that param can only be a number
return param + 1;
}
// Here TypeScript should know that param can only be a string
return "one more " + param;
}

const stringResult = increase("apple"); // "one more apple"
// Here TypeScript should know that stringResult is a string

const numResult = increase(2); // 3
// Here TypeScript should know that numResult is a number

Playground Link

这还允许您提供单独的 Intellisense,详细说明根据参数类型的行为差异。

如果您绝对需要该函数是箭头函数,请参阅 this answer on how to overload an arrow function

因为 JavaScript 没有类型,所以它无法提供真正的函数重载。为了解决这个问题,TypeScript 允许您提供额外的函数签名来表达重载。然后,函数的实际实现必须手动区分参数类型并选择适当的行为。另请参阅TypeScript Handbook .

关于具有通用联合约束的 TypeScript 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65004521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com