[英]typescript mark function as implementing an interface
I want to indicate that a function is expected to implement a certain interface.我想指出一个 function 有望实现某个接口。
For example:例如:
import { BrowserEvents, eventHandler, Event } from './browser-events';
export function setup(){
const browserEvents = new BrowserEvents();
browserEvents.onClicks(handleClicks);
function handleClicks(ev: Event) {
ev.preventDefault();
}
}
I would like to tell typescript that handleClicks
should match type eventHandler
.我想告诉 typescript
handleClicks
应该匹配类型eventHandler
。 Obviously, if the signature of handleClicks
doesn't match onClicks
, ts will throw an error.显然,如果
handleClicks
的签名与onClicks
不匹配,ts 会抛出错误。 But I would like to show the error 'at the source' like this syntax:但我想像这样的语法在“源头”显示错误:
// (not valid syntax!)
function handleClicks(ev: Event) implements eventHandler {
ev.preventDefault();
}
I could also use the function as a variable, like so, but it would force me to move the function before its usage:我也可以使用 function 作为变量,就像这样,但它会迫使我在使用 function 之前移动它:
const handleClicks: eventHandler = (ev: Event) => {
ev.preventDefault();
}
browserEvents.onClicks(handleClicks);
so, is there a syntax to force a regular function to comply to a signature?那么,是否有强制常规 function 遵守签名的语法?
think you might be able to do something like this:认为您可能可以执行以下操作:
(but not sure what you're trying to return so I have typed it as void
) (但不确定您要返回什么,所以我将其输入为
void
)
interface FunctionInterface {
(e: eventHandler): void;
}
function f1(e): FunctionInterface {
e.preventDefault();
}
const f2: FunctionInterface = e => {
e.preventDefault()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.