0

有一个不支持 typescript 的外部 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 包创建类型定义,因为我想在我的 typescript 项目中使用它,我刚开始学习 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 的包

4

1 回答 1

0

您没有从声明的模块中导出任何内容package-without-ts

改成这个

declare module 'package-without-ts' {
  class ClassA {
    public options: object
    constructor (options: IOptions) // {} in your code is invalid
  }

  export = ClassA // special syntax for commonjs style export
}
于 2019-02-15T13:01:38.430 回答