首页 > 解决方案 > javascript to typescript:混合基于原型的对象和基于类的对象

问题描述

我正在尝试将 javascript 原型与基于类的混合,如下所示:

function Cat(name) {
    this.name = name;
}
Cat.prototype.purr = function(){
    console.log(`${this.name} purr`);
}
Cat.prototype.meow = function(){
    console.log(`${this.name} meow`);
}


class Tiger extends Cat {
    constructor(name) {
        super(name);
    }

    meow() {
        console.log(`${this.name} roar`);
    }
}

上面的JS代码是有效的。然后我将代码转换为打字稿,如下所示:

function Cat(this : any, name : string) {
    this.name = name;
}
Cat.prototype.purr = function(){
    console.log(`${this.name} purr`);
}
Cat.prototype.meow = function(){
    console.log(`${this.name} meow`);
}


// error: Type '(this: any, name: string) => void' is not a constructor function type.
class Tiger extends Cat {
    constructor(name : string) {
        super(name);
    }

    meow() {
        console.log(`${this.name} roar`);
    }
}

Tiger 类不接受 Cat 类作为其基类。(在 JS 中有效,但在 TS 中无效)。我无法将 Cat 更改为标准类语法,因为我需要将 .prototype 访问权限指向另一个 JS 库。

任何人都可以修复上面的 TS 代码?也许添加一些.d.ts定义。

注意:添加// @ts-ignore有效,但我不能这样做,因为 VS-code 智能感知不起作用。

标签: javascripttypescriptclassprototype

解决方案


好吧,你可以尝试做这样的事情

interface CatClass {
  name: string
  purr(): void
  meow(): void

  new (name: string): CatClass
}

const Cat = function(this: CatClass, name: string) {
  this.name = name
} as unknown as CatClass
// Then add functions to prototype and everything should be fine

问题是为什么你首先要这样做,为什么不把它重写为一个普通的类呢?似乎没有任何关于如何在没有这个as unknown as CatClass东西的情况下键入此类函数类的信息(这似乎有点 hack 但很好),也许是因为没有人需要这样做,我理解。无论如何,编译后所有类都成为函数


推荐阅读