javascript - 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 智能感知不起作用。
解决方案
好吧,你可以尝试做这样的事情
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 但很好),也许是因为没有人需要这样做,我理解。无论如何,编译后所有类都成为函数
推荐阅读
- c++ - 我不能对 fstream() 的参数使用操作符 ""sv 吗?
- registry - 尝试加载 ActiveX 控件时如何处理“0x80020009”?
- node.js - 从终端 react.js 运行脚本的问题
- c++ - 如何避免哈希表中的冲突?
- electron - 如何在没有 github 的情况下离线安装电子
- php - PHP我想知道这一行的错误是什么
- spring-boot - 如何在 Spring Stream Kafka 处理中重用流函数目标
- javascript - 使用谷歌日历 api 在一个删除请求中删除多个事件(无批处理)?
- selenium - Selenium Chromedriver 不加载页面
- linux-kernel - 寻找有关 Linux 内核如何与 NVME 配合使用的详细信息