Typescript 函数的类型化数组-使用此引用
我正在尝试创建一个接口,该接口使用一系列函数和一个this-guard来定义接口,如下所示:Typescript 函数的类型化数组-使用此引用,typescript,Typescript,我正在尝试创建一个接口,该接口使用一系列函数和一个this-guard来定义接口,如下所示: interface MyInterface { myFunctions: ((this:MyInterface, somevar: string): void)[]; } class Myclass implements MyInterface { myFunctions: ((this:Implementation, somevar: string): void)[]; useFunct
interface MyInterface {
myFunctions: ((this:MyInterface, somevar: string): void)[];
}
class Myclass implements MyInterface {
myFunctions: ((this:Implementation, somevar: string): void)[];
useFunction (): void {
this.myFunctions[0](somevar);
}
}
但是,当我尝试按如下方式使用它时:
interface MyInterface {
myFunctions: ((this:MyInterface, somevar: string): void)[];
}
class Myclass implements MyInterface {
myFunctions: ((this:Implementation, somevar: string): void)[];
useFunction (): void {
this.myFunctions[0](somevar);
}
}
下面的错误发生了
类“Myclass”不正确地实现了接口“MyInterface”
有人知道我是如何实现的???首先,函数类型是用
=>
声明的,而不是:
interface MyInterface {
myFunctions: ((this:MyInterface, somevar: string) => void)[];
}
其次,为什么类中有this:Implementation
,而不是接口中声明的this.MyClass
或this.MyInterface
?它应该是一致的-类和接口中的this.Implementation
,或者接口中的this.MyInterface
和类中的this.MyClass
然后,在javascript(和typescript)中,为了调用函数并将其设置为this
上下文,函数名后面必须紧跟(
,例如this.useFunction()
)
您有this.myFunctions[0](somevar)
,这意味着您正在将myFunctions
的第一个元素作为自由函数调用,而不设置其this
上下文。您需要使用以下方法显式设置this
:
你的类实现与你的接口不同,所以这是不允许的。我也不确定一个接口怎么会有一个实现自己的函数……感谢你的帮助,关于函数如何声明的第一个错误就是我的错,就像你在原始源代码中说的那样。