Typescript 试图在项目中编写自己类的协议扩展函数,但没有成功
我通过编写类似于Vue类和数组等的函数进行扩展,它可以工作,但不适用于我自己定义的类型 CSVue.tsTypescript 试图在项目中编写自己类的协议扩展函数,但没有成功,typescript,Typescript,我通过编写类似于Vue类和数组等的函数进行扩展,它可以工作,但不适用于我自己定义的类型 CSVue.ts import '@/cs/extensions/CSLang' import Vue from 'vue' import { event } from '@/cs/event/CSEvent' export class CSVue extends Vue { eventDestroyed = event() mounted() { // console.log(`mou
import '@/cs/extensions/CSLang'
import Vue from 'vue'
import { event } from '@/cs/event/CSEvent'
export class CSVue extends Vue {
eventDestroyed = event()
mounted() {
// console.log(`mounted ${this.constructor}`)
}
updated() {
// console.log(`updated ${this.constructor}`)
}
destroyed() {
// console.log(`destroyed ${this.constructor}`)
this.eventDestroyed.fire()
}
}
CSVue+Extension.ts
import { CSVue } from '@/cs/CSVue'
declare module '@/cs/CSVue' {
interface CSVue {
updateOnWindowEvent(type: string, method: () => void): void
}
}
CSVue.prototype.updateOnWindowEvent = function (type: string, method: () => void): void {
method()
window.addEventListener(type, method)
this.eventDestroyed.listen(() => { window.removeEventListener(type, method) })
}
然后在类中调用它,在函数中扩展CSVue,如下所示:
this.updateOnWindowEvent('resize', () => this.windowHeight = window.innerHeight)
我得到错误:TypeError:this.updateOnWindowEvent不是函数
所以我的解决方法就是在CSVue类中简单地定义函数