首页 > 解决方案 > 在 typescript 类型中引用静态方法:自动拾取方法签名

问题描述

我有一个带有静态方法的类:

class Application {
  static get(): string {
    ...
  }
}

现在我想在另一个类中引用这个静态 get 方法。我知道我可以这样做:

class Caller {
  klass: { get (): typeof Application["get"] }
}

如果该方法不带参数,这很容易工作。编辑:请在下面查看为什么这是错误的

现在,如果我添加一个参数:

class Application {
  static get(argument: string): string {
    ...
  }
}

...我还必须更改Caller(以及具有此签名的所有其他类):

class Caller {
  klass: { get (argument: string): typeof Application["get"] }
}

有没有办法避免这种情况?因为很明显,klass.get总是遵循 的函数签名Application.get。有没有办法告诉打字稿这样的事情:

class Caller {
  klass: { get (signatureof typeof Application["get"]): typeof Application["get"] }
}

编辑: 其实我刚刚意识到上面是错误的: 我实际上定义get()返回的行为typeof Application["get"]

我给了它一个新的镜头:

class Caller {
  klass: {
    [Key in keyof typeof Application]: typeof Application[Key]
  }
}

...虽然我还没有看到这是否能解决它,brb。


编辑2:两种方式似乎都是可能的:


// reference all properties
class Caller {
  klass: {
    [Key in keyof typeof Application]: typeof Application[Key]
  }
}

// or if only one specific thing is needed
// reference one property
class Caller {
  klass: {
    get: typeof Application["get"]
  }
}

不幸的是,如果引用方法更复杂,例如get()访问定义的静态属性Application,这会变得更复杂,因为打字稿会抱怨那些没有找到(如果只引用了方法,而不是每个属性)。

所以我认为要走的路是引用所有属性以确保安全。

标签: typescriptstatic

解决方案


您可以使用 引用静态方法的类型typeof Class['methodName']。您可以直接将此类型用作 的类型get

class Caller {
  klass: {
    get: typeof Application["get"]
  }
}

这将意味着get与 的方法相同的get类型 Applicationtypeof Application["get"]是方法的整个函数签名,所以对参数或返回类型的任何更改都会反映在getonklass


推荐阅读