Typescript: Initialize an empty NodeListOf

Viewed 718

I am struggling in TS with querySelectorAll. I want to access any HTML element with this selector, no matter if it is a button, input and so on.

For querySelector I did something like this (which works fine):

function selector(element: HTMLElement, selector: string): HTMLElement | null {
    return element.querySelector(selector);
}

const element: HTMLElement | null = selector(document.body, '.my-button');

This is my similar method for querySelectorAll:

function selectorAll(element: HTMLElement, selector: string): NodeListOf<HTMLElement> {
    return element.querySelectorAll<HTMLElement>(selector);
}

Now my issue is that I can not initialize an empty node list. For example:

let buttons: NodeListOf<HTMLElement> = [];
buttons = selectorAll(document.body, 'button');

The compiler says: The property 'item' is missing in type 'never[]' but required in type 'NodeListElement'.

So what is the correct syntax for initializing an empty NodeListOf type?

1 Answers

There is no easy way to create an object with the NodeList interface other than calling querySelectorAll and related DOM APIs.

One alternative is to use array instead of NodeList.

let buttons: Array<HTMLElement> = [];
buttons = Array.from(selectorAll(document.body, 'button'));
Related