在 Typescript 中重载通用箭头函数的语法错误

Jos*_*hua 7 generics typescript arrow-functions

interface Foo1 {
  (param: number): number
  (param: string): string
}

const foo1: Foo1 = (param: number | string) => param as any
const foo2 = <T>(param: T) : T => param 

interface Foo3<T1, T2> {
  (param: T1): T1
  (param: T2): T2
}

const foo3: Foo3<T1, T2> = <T1, T2>(param: T1 | T2) => param as any
// [ts] Cannot find name 'T1'. [2304]
// [ts] Cannot find name 'T2'. [2304]
Run Code Online (Sandbox Code Playgroud)

我在 StackOverflow 上搜索过,但问题只涉及其中一个或没有回答问题。

bri*_*web 0

您可能正在寻找这样的东西:

interface Foo {
  <T1 extends number>(param: T1): T1;
  <T2 extends string>(param: T2): T2;
}

const foo: Foo = <T1, T2>(param: T1 | T2) => param;

let numberResult = foo(1); // result is 1
let stringResult = foo("test") // result is "test"
let errorResult = foo({test:"hello"}) //error
Run Code Online (Sandbox Code Playgroud)

游乐场链接