具有泛型函数返回具有相同泛型的函数

时间:2020-08-28 19:52:47

标签: typescript

例如,我希望以下函数返回一个可以接受任何字符串或任何数字的函数,这取决于调用初始函数的方式,但它仅接受等于a的字符串或数字:

function foo<A extends string | number>(a: A) : (b: A) => boolean {
  return (b) => a === b;
}

foo("test") // creates a function that only accepts "test", want one that accepts any string.
foo(3) // creates a function that only accepts 3, want one that accepts any number.

如何键入此函数,使其按需工作?

  • 进行编辑以阐明问题所在

2 个答案:

答案 0 :(得分:2)

如果您只删除extends string,它似乎可以满足您的要求

function foo<A>(a: A) : (b: A) => boolean {
  return (b) => a === b;
}

Typescript Playground Link

如果您想限制输入类型并且仍然让它们通过,则可以执行以下操作

function foo(a:string): (b:string) => boolean
function foo(a:number): (b:number) => boolean
function foo(a:boolean): (b:boolean) => boolean

function foo (a: string|number|boolean) : (b: string|number|boolean) => boolean {
  return (b) => a === b;
}

foo("test")("a")  //expects string
foo(1)(2)  //expects number

Playground Link

答案 1 :(得分:-1)

似乎这样做的方法是使用重载:

function foo(a1: number): (a2: number) => boolean; 
function foo(a1: string): (a1: string) => boolean;
function foo(a1: number | string): (a2: number|string) => boolean {
  return (a2) => a1 === a2;
}