如何为返回类的外部包创建打字稿定义文件

时间:2019-02-15 11:34:40

标签: javascript node.js typescript ecmascript-5 type-definition

有一个不支持打字稿的外部npm软件包:

const ClassA = class ClassA {
  constructor(options) {
    this.test = options => this.client(options)
    .then(ClassA._validateAddress.bind({
      ...options,
      address: this.address
    }))
    this.someMethod = options => this.test(options);

    ClassA._validateOptions(options);
    ClassA._validateAddress(options.address);

    this.address = options.address;
    this.log = options.log || console;
    this.client = otherPackage.defaults({
      defaultAddress: this.address,
      returns: true
    });
  }

  static _validateOptions(options) {
    if (!options) {
      throw new Error('test error')
    }
    if (!isObject(options)) {
      throw new Error('options is not an object');
    }

    function isObject(value) {
      const type = typeof value
      return value !== null && (type === 'object' || type === 'function')
    }
  }
}

module.exports = ClassA

我正在TypeScript项目中创建类似的内容(仍在JS中,将转换为TS):

const ClassA = require('package-without-ts')

const myClient = class ClassB extends ClassA {
  constructor(options) {
    super(...arguments)

    this.customMethod = options => Object.assign(options, {
      test: true
    })
  }
}


const options = {
  a: 1,
  b: 2
}
const client = new myClient(options);

如何为ClassA包创建类型定义,因为我想在我的打字稿项目中使用它,所以我才刚刚开始学习TS,所以这对我来说有点复杂

我尝试将TS样式的类或接口提取到.d.ts文件中,但对我没有任何作用

/// <reference types="node" />


interface IOptions {
  address: string,
  log: object,
}

declare module 'package-without-ts' {
  class ClassA {
    public options: object
    constructor (options: IOptions) {
    }
  }
}

我希望我的TS项目可以使用不支持TS的程序包

1 个答案:

答案 0 :(得分:0)

您没有从声明的模块> | dec_to_bin(8) < | "1000" 中导出任何内容。

更改为此

package-without-ts