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

2024-03-04

我有一个第三方库,它具有以下 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
}

Usage:

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实际上指的是一个类型instance类的,而不是类(构造函数)本身。

相反,你会想使用typeof IMachine:

const Machine: typeof IMachine = require('lib')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用类为第三方库创建类型 的相关文章

随机推荐