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

问题描述 投票:0回答:1

有一个外部npm包不支持typescript:

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的软件包

javascript node.js typescript ecmascript-5 type-definition
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
}
© www.soinside.com 2019 - 2024. All rights reserved.