【问题标题】:Defining type of function which I want to take as an input : Typescript定义我想作为输入的函数类型:Typescript
【发布时间】:2021-04-05 21:22:22
【问题描述】:

我想确保我的输入只接受下面的函数作为参数:

  async getAll<T extends Entity>(url: string, params?: any): Promise<T[]> {
     // func body
  }

我的功能

  setFunc(getAllFunc: any){
    this.func = getAllFunc;
  }

我想用自定义类型替换any

提前致谢。

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    您可以为此使用接口或类型。

    类型:

    type TGetAllFunc<T extends Entity> = (url: string, params? : any) => Promise<T[]>;
    

    界面:

    interface IGetAllFunc<T extends Entity> {
        (url: string, params? : any): Promise<T[]>;
    }
    

    那么你可以将其中一个传入函数中(我这里传入了Interface):

    setFunc(getAllFunc: IGetAllFunc<Entity>){
      this.func = getAllFunc;
    }
    

    【讨论】:

    • 当我替换 any 时显示 Generic type 'IGetAllFunc&lt;T&gt;' requires 1 type argument(s)
    • 抱歉,忘记将 T 传递给 IGetFunc,我更新了答案。现在可以用了吗?
    【解决方案2】:

    根据您的函数,getAll 函数的类型如下:

    type FunctionType<T> = (string, any) => Promise<T[]>;
    

    然后您可以重写您的函数setFunc 以获取函数类型。

    setFunc(getAllFunc: FunctionType<T>){
        this.func = getAllFunc;
    }
    

    您似乎将getAllFunc 设置为类属性,这意味着您需要让您的类也具有通用性。所以你的班级看起来像这样,

    type FunctionType<T> = (string, any) => Promise<T[]>;
    
    class SomeClass<T> { // named SomeClass for brevity, use your own name here
        func: FunctionType<T>
    
        setFunc(getAllFunc: FunctionType<T>){
            this.func = getAllFunc;
        }
    
        /* ... */
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2020-06-04
      • 2016-11-22
      • 1970-01-01
      相关资源
      最近更新 更多