Javascript 如何为函数定义Typescript接口?
我正在定义以下Typescript接口。clickCustomButton1应该不返回任何内容,但我不确定如何指定它Javascript 如何为函数定义Typescript接口?,javascript,typescript,Javascript,Typescript,我正在定义以下Typescript接口。clickCustomButton1应该不返回任何内容,但我不确定如何指定它 interface IButtonTemplate { clickCustomButton1: (); // How can I say this should return nothing? // more code here } 我在我的代码中这样使用: clickCustomButton1: null 随后: newTopicTests = () =&g
interface IButtonTemplate {
clickCustomButton1: (); // How can I say this should return nothing?
// more code here
}
我在我的代码中这样使用:
clickCustomButton1: null
随后:
newTopicTests = () => {
}
clickCustomButton1 = this.newTopicTests();
这给了我一个错误,说:
Error 2 Cannot convert 'void' to '() => boolean'
有人能告诉我我做错了什么吗?我想我需要做的是指定clickCustomButton1和NewTopItems不返回任何内容。但是如何使用Typescript实现这一点呢?问题是因为lambda
()=>{}
被键入为():void
,因为它不返回任何内容,因此没有推断出[other]类型
因此,给定f=()=>{}
,表达式f()
也被键入为void
——但clickCustomButton1必须在声明时返回一个布尔值
使用以下lambda时进行比较,该lambda的类型为():boolean
,现在该lambda的类型有效:
newTopicTests = () => true
查看此问题的另一种方法是将原始代码编写为:
newTopicTests = (): boolean => {}
(这也将无法编译,但将显示更接近其源位置的错误。)
在问题更新之后
要在接口中声明不返回任何内容的方法,请使用:
clickCustomButton1(): void;
要声明类型为():void
的成员,请使用
clickCustomButton1: () => void;
还要注意的是,null
是一些东西,而void则不代表任何东西。user2864740-很抱歉,但我不确定我是否理解你的意思。我在问题中添加了一行,询问是否有人可以向我展示如何做到这一点,并在我分配给clickCustomButton1的任何内容都应满足不返回任何内容的条件时使其工作。