简体   繁体   English

如何将 js 函数构造函数转换为打字稿?

[英]How to convert a js function constructor to typescript?

I'm moving from js to typescript and i have some challenges.我正在从 js 转向打字稿,但我遇到了一些挑战。

I need to convert a constructor function to the equivalent of typescript.我需要将构造函数转换为相当于打字稿的函数。

The function in js is like so: js中的函数是这样的:

export default function(address) {
  var self = this ;
  self.address = address;
  
  self.init = function(){
    //some code
  }

  self.onClick = function() {
   // some code
  }
}

I tried to convert it but it complains in this keyword.我试图转换它,但它在this关键字中抱怨。 (missing anotation) (缺少注释)

const Address: (address: string) => void = function (address: string) {
   this.address = address;
 }

Address.prototype.init = function() {
  // some code here
}

export default Address

and I'm planning to call it inside react component, from another file, like so: new (Address as any)( address_here ));我打算在 react 组件中从另一个文件中调用它,如下所示: new (Address as any)( address_here ));

I'm having the issue with the this so I haven't checked if the prototype function works too.我遇到的问题this所以如果原型功能也工作我没有检查。

You can create a class and add methods to it.您可以创建一个类并向其添加方法。

Note: All methods in TS Class goes to prototype and properties to object.注意: TS 类中的所有方法都转到原型和属性到对象。 You can even define a static method which is similar to adding method to function in ES5你甚至可以定义一个静态方法,类似于在 ES5 中为函数添加方法

export default class SetAddress {
  constructor( public readonly address: string ) {}

  public init(): void {}

  public onClick(event: HTMLEventAction): void {}
}

You can even test at TS PlayGround .您甚至可以在TS PlayGround 进行测试。 You will have to set the target version to ES5您必须将目标版本设置为 ES5

在此处输入图片说明

Well you can use class declaration syntax:那么你可以使用类声明语法:

export default class Address{
    constructor({address}:Object){
       this.address : String = address;
    }

    init():void{ // or your type of return
      // some code
    }

    onClick():void{ // or your type of return
      // some code
    }
}

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

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