I listen to the window.matchMedia changes
I have this error: Parameter 'event' implicitly has an 'any' type.
What TS type should I specify here for the event object?
const mobileMediaQuery = window.matchMedia("(max-width: 699px)");
mobileMediaQuery?.addEventListener("change", processViewSizeChange);
function processViewSizeChange(event) {
console.log('media query changed! →', event.matches);
}
where on the internet to look up typescript global types? in case I need to find something similar in the future.
CodePudding user response:
You can use TypeScript to learn about the types that you need. Here's an example in your case. You know that you need to supply the "change" event type, and that you need to supply a callback function for the listener, but you're not sure how to type the callback function, so just leave it out at first:
const mobileMediaQuery = window.matchMedia('(max-width: 699px)');
mobileMediaQuery.addEventListener('change', ); /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expected 2-3 arguments, but got 1.(2554) */
If you don't include the second argument to mobileMediaQuery.addEventListener, you'll get a compiler error diagnostic like that.
But if you are using an IDE which includes the TypeScript Language Server and something like IntelliSense (e.g. VS Code, or the TypeScript Playground), you can mouse over the addEventListener method to see its signature:
(method) MediaQueryList.addEventListener<"change">(type: "change", listener: (this: MediaQueryList, ev: MediaQueryListEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void ( 1 overload)
As you can see from the signature, the listener is the second argument, and the type of the event parameter in the listener is MediaQueryListEvent. So you can type your listener function like this:
function processViewSizeChange(event: MediaQueryListEvent): void {
console.log('media query changed! →', event.matches);
}
