使用类为 3rd 方库创建类型 [英] Create typings for 3rd party library using class

查看:25
本文介绍了使用类为 3rd 方库创建类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a third party library which has this ES6 class signature:

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

我试图为这个类创建类型声明,但出现了一些错误:

I tried to create type declarations for this class but I get some errors:

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.

我在这里做错了什么?

推荐答案

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

Your declaration is fine. The problem is this line:

const Machine: IMachine = require('lib')

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

IMachine actually refers to the type of an instance of the class, not the class (the constructor) itself.

相反,您需要使用 typeof IMachine:

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

这篇关于使用类为 3rd 方库创建类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆