【问题标题】:Create typings for 3rd party library using class使用类为 3rd 方库创建类型
【发布时间】:2020-01-12 01:45:03
【问题描述】:

我有一个具有此 ES6 类签名的第三方库:

class Machine {
  constructor(options)
  static list(callback)
  create(options, callback)
}

我尝试为此类创建类型声明,但出现一些错误:

export declare class IMachine {
  public constructor(opts: MachineOptions)
  public static list(callback: (err?: Error, machines?: IMachine[]) => void): void
}

declare interface MachineOptions {
  name: string
}

用法:

const Machine: IMachine = require('lib')
Machine.list((err: Error, machines: IMachine[]) => { } //  error TS2576: Property 'list' is a static member of type 'IMachine'


const machine = new Machine({name: 'some name'}) // error TS2351: This expression is not constructable. Type 'IMachine' has no construct signatures.

我在这里做错了什么?

【问题讨论】:

标签: typescript typescript-typings


【解决方案1】:

你的声明很好。问题是这一行:

const Machine: IMachine = require('lib')

IMachine实际上是指类的实例的类型,而不是类(构造函数)本身。

相反,您需要使用typeof IMachine

const Machine: typeof IMachine = require('lib')

【讨论】:

  • 即使第三方库有module.exports = Machine?
  • 是的。对于 TypeScript 中的一般类,这实际上是正确的。每当类名用作 type 时,它指的是该类的一个实例。如果你想要类本身,构造函数和静态上下文你需要使用typeof
  • 这样我得到error TS2339: Property 'create' does not exist on type 'typeof IMachine'.
  • 这似乎来自您尚未发布的部分代码。也许像Machine.create(...) 之类的?
  • 我的错。我直到现在才在 TypeScript 类上指定它。
猜你喜欢
  • 2016-10-22
  • 2021-01-30
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2012-06-27
  • 1970-01-01
  • 2018-10-09
相关资源
最近更新 更多