【问题标题】:Typescript: How type a function using generic type in this case?Typescript:在这种情况下如何使用泛型类型键入函数?
【发布时间】:2020-02-27 00:56:20
【问题描述】:

我有这个类型定义

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&lt;T&gt; = (value) =&gt; 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}
}

【问题讨论】:

  • 你真的需要类型别名吗?也许你可以function myFunc&lt;T&gt;(value: T) : T { return value; }
  • @AlekseyL。我更新了我的问题以回答你的问题。
  • 问题是:你是否在多个地方使用该类型?如果是,请显示用例。否则我的建议仍然有效 - 根据需要添加尽可能多的重载

标签: typescript typescript-types


【解决方案1】:

到目前为止,我还没有看到 FuncType 作为具体重载函数的泛型类型别名的用例。您能否改为将其作为 generic 重载函数的 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

【讨论】:

    【解决方案2】:

    总结一下,简单的从

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      相关资源
      最近更新 更多