【发布时间】:2021-03-08 07:11:05
【问题描述】:
我无法理解如何在 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 | number。
我希望在 TypeScript 中实现什么?如果是这样,我做错了什么?
【问题讨论】:
-
问题是,例如,调用
increase<4>(4)应该产生4,因为这是通用参数。但是,您param + 1不会返回。如果您调用increase<"hello">("hello"),则与字符串相同 -
哦,我以为它只是意味着如果通用参数是一个字符串,那么输出也将是一个字符串(并且可能是一个不同的字符串)。有什么办法吗?
标签: typescript