简体   繁体   English

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

[英]How to create typescript definition file for external package which returns class

There is an external npm package which doesn't support 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

I am creating something like this in my TypeScript project (still in JS, will be converted to TS): 我正在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);

How to create a type definition for ClassA package, as I want to use it with my typescript project, I just started learning TS so this is bit complex for me to understand 如何为ClassA包创建类型定义,因为我想在我的Typescript项目中使用它,所以我才刚刚开始学习TS,所以这对我来说有点复杂

I tried extracting class or interfaces in TS style to .d.ts file, but nothing works for me 我尝试将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) {
    }
  }
}

I expect my TS project to work with package which doesn't support TS 我希望我的TS项目可以使用不支持TS的软件包

You didn't export anything from your declared module package-without-ts . 您没有从声明的模块package-without-ts导出任何内容。

Change to this 改成这个

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM