打字稿:在这种情况下如何使用通用类型键入函数?

Typescript: How type a function using generic type in this case?

我有这个类型定义

type FuncType<T> = (value: T) => T

我想使用这种类型实现一个函数,如下所示:

const myFunc: FuncType<T> = (value) => value;

并按如下方式使用它:

const a: string = myFunc<string>('a');
const b: number = myFunc<number>(2);

但是,当然,前一行 const myFunc: FuncType<T> = (value) => value; 没有有效的语法。

应该怎么写?


注意: 我找到了一个使用中间函数的解决方法,但最好避免这种无用的柯里化 (我不能在我的实际用例中使用它,因为它与反应挂钩有关,反应挂钩不能容忍柯里化):

const myFunc = <T>(): FuncType<T> => (value) => value;
const a: string = myFunc<string>()('a');
const b: number = myFunc<number>()(2);


为什么要用这个类型别名不能直接写?

const myFunc = <T>(value: T): T => value;

因为在我的实际用例中,我函数的类型定义并不是那么简单。

看起来像这样:

interface FuncType<T> {
  (args: {arg1: T}): {res1: T}
  (args: {arg1: T, arg2: T}): {res1: T, res2: T}
}

到目前为止,我没有看到 FuncType 作为具体重载函数的通用类型别名的用例。你能不能让它成为 concrete 重载函数的 generic 类型别名?像这样:

interface FuncType {
  <T>(args: { arg1: T }): { res1: T }
  <T>(args: { arg1: T, arg2: T }): { res1: T, res2: T }
}

然后 FuncType 将始终引用接受任何 T 的内容,您可以按照自己的方式使用它:

const myFunc: FuncType =
  (value: { arg1: any, arg2?: any }) => ({ res1: value.arg1, res2: value.arg2 });

const a = myFunc<string>({ arg1: "" }); // { res1: string; }
const b = myFunc<number>({ arg1: 1, arg2: 2 }); // { res1: number; res2: number; }

希望能满足您的需求。祝你好运!

Link to code

综上所述,只需将

type FuncType<T> = (value: T) => T

type FuncType = <T>(value: T) => T