Is there a way in Typescript to ensure that a function implements a specific interface?
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 want to explicitly declare that handleClicks
must match type eventHandler
. Currently, if the signature of handleClicks
does not align with onClicks
, TypeScript will throw an error. But is there a syntax available to indicate this requirement directly in the code like so:
// (not valid syntax!)
function handleClicks(ev: Event) implements eventHandler {
ev.preventDefault();
}
I could also define the function as a variable, but it would require reordering the code like this:
const handleClicks: eventHandler = (ev: Event) => {
ev.preventDefault();
}
browserEvents.onClicks(handleClicks);
So, is there a method to enforce a regular function to adhere to a specific signature in TypeScript?