如何告诉打字稿从参数对象中获取泛型类型?

How to tell typescript to get generic type from argument object?

假设我有以下定义:

interface Options<T = any, K = void> {
  scope?: K,
  success: (this: K, result: T) => any,
  failure: (this: K, result: T) => any
}

interface HttpClient {
  request<T>(opts: Options<T>)
}

根据上面的定义,typescript 不会在 successfailure 中为我提供正确的类型。我如何告诉 Typescript K 应该是第一个参数的 scope 属性。

用法示例:

class Abc {
  //...

  save() {
    var client = new HttpClient()
    client.request({
      scope: this,
      success: function(result) {
        this // here no intellisense
      }
    })
  }

  notify(event, data) {
    this.element.dispatchEvent(new CustomEvent(event, { detail: data }));
  }
}

当您声明 request<T>(opts: Options<T>) 时,您正在将类型 K 固定为默认值 void。如果您想将该类型变量保留为某种变量,它必须仍然是 request<T,K>.

中的类型参数

此代码正确地将 this 的类型推断为 this:

interface Options<T = any, K = void> {
  scope?: K,
  success: (this: K, result: T) => any,
  failure?: (this: K, result: T) => any
}

class HttpClient {
  request<T, K>(opts: Options<T, K>) : any {}
}

class Abc {
  //...

  save() {
    var client = new HttpClient()
    client.request({
      scope: this,
      success: function(result) {
        this // here intellisense offers `notify` and `save` completion
      }
    })
  }

  notify(event, data) {
    this.element.dispatchEvent(new CustomEvent(event, { detail: data }));
  }
}

其他较小的代码更改:我不得不将 failure 设为可选,将 HttpClient 设为 class 只是为了获得一些不会抱怨任何更高级别的代码notify().