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

时间:2019-10-31 15:59:34

标签: typescript typescript-types

我有这个类型定义

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;没有有效的语法。

应如何编写?


注意: 我找到了使用中间函数的解决方法,但最好避免这种无用的currying (我不能在我的实际用例中使用,因为它与react挂钩相关,而react hooks不能容忍currying)

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}
}

2 个答案:

答案 0 :(得分:2)

到目前为止,我还没有看到FuncType的用例是具体的重载函数的通用类型别名。您是否可以将其作为泛型重载函数的 concrete 类型别名?像这样:

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

答案 1 :(得分:0)

总结起来,只需从

进行更改
type FuncType<T> = (value: T) => T

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