Typescript:如何指定具有多个泛型的函数的结果



如何指定具有多个泛型的函数的结果?这是我不工作的代码:

const getter = <T, K>(age: T, name: K):T,K => `${age} and ${name}`;

函数只能返回一个值,因此不清楚您真正想要的是什么。

也就是说,你在寻找一个字符串模板文字解决方案吗?

例如,您可以将返回类型键入为${T} and ${K}以返回特定的字符串类型。

const getter =
<
T extends number,
K extends string
>(
age: T,
name: K
): `${T} and ${K}` => `${age} and ${name}`;
const test = getter(50, "Gertrude") // test is of type "50 and Gertrude"
const typeError: "25 and Mary" = getter(50, "Gertrude") // error
// Type '"50 and Gertrude"' is not assignable to type '"25 and Mary"'.(2322)

注意T extends numberK extends string。这就是您要求泛型是进入函数的特定类型的方式。

游乐场


或者您可以返回一个元组:

[T, K]

或者一个物体:

{ [name in K]: T }

因此,弄清楚泛型类型如何适合您的返回类型,然后将它们放在正确的位置。

看起来您的函数只是返回一个字符串。。?

const getter = <T, K>(age: T, name: K):string => `${age} and ${name}`;

工作TS游乐场

最新更新