Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
Typescript Type for window.matchMedia change event object

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
}

Final code at TS Playground

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda