typescript - 使用类为第三方库创建类型

标签 typescript typescript-typings

我有一个具有此 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.

我在这里做错了什么?

最佳答案

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

const Machine: IMachine = require('lib')

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

相反,您需要使用typeof IMachine:

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

关于typescript - 使用类为第三方库创建类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868450/

相关文章:

typescript - 如何使用 jest 模拟 typescript 中的外部依赖关系

javascript - 无法从 Angular 中的响应数据分配数据

node.js - 从 TypeScript 中的依赖项访问类型声明

arrays - 可以在 Typescript 中定义重复的元组吗

typescript - Azure devops 失败 TS build : ' Type ' false' is not assignable to type 'Date' : but type is defined as 'Date | boolean' and build works locally

javascript - 如何使用映射过滤嵌套数组并使用对象过滤

javascript - 如何在触发任何验证之前根据条件强制输入大写字母?

javascript - JSON.parse 有困难吗?

typescript - 从类的属性和方法中提取特定类型并将其添加到接口(interface)

reactjs - react 网格布局与 typescript 不工作