【问题标题】:Return type of a function based on param name基于参数名称的函数返回类型
【发布时间】:2018-09-05 13:46:46
【问题描述】:

假设我有一个这样的界面MyInterface

interface MyInterface = {
    param1: string;
    param2: number;
}

有没有办法声明函数的返回类型,假设函数的参数值本身就是MyInterface的参数:

class MyClass<T = MyInterface> {
   constructor(private params: T) {
     // ...
   }

    // The question comes here:
   get(value: keyof T): T[value] { // Obviously this doesn't work
      return this.params[value];
   }
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您需要捕获value 的类型,例如使用另一个泛型:

    type MyInterface = {
        param1: string;
        param2: number;
    }
    
    class MyClass<T = MyInterface> {
       constructor(private params: T) {
         // ...
       }
    
       // Fixed 
       get<G extends keyof T>(value:G): T[G] {
          return this.params[value];
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2019-06-07
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2018-08-10
      • 2017-06-01
      相关资源
      最近更新 更多