querySelector Generic Types File Input

querySelector with a generic parameter types the result as HTMLInputElement, so files, checked, and value arrive typed instead of as plain Element.

TypescriptFile Upload

Code

typescriptsnippet
16 lines
const input = document.querySelector<HTMLInputElement>('input[type="file"]');

if (input) {
  input.addEventListener('change', () => {
    // 泛型让 input 直接携带 HTMLInputElement 的属性;files 是 FileList | null
    const file = input.files?.[0];
    if (file) {
      console.log('picked:', file.name, file.type, file.size, 'bytes');
    } else {
      console.log('selection cleared');
    }
  });
}

const accept = input?.getAttribute('accept') ?? 'no restriction';
console.log('accepts:', accept);

How it works

Module-level bindings hold the data — input, accept — with no function scope in between.

What to watch for

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Running the file prints labeled results such as picked:, selection cleared, accepts: — each operation’s effect is visible in the output.

Statements that matter

const accept = input?.getAttribute('accept') ?? 'no restriction';
input.addEventListener('change', () => {
// 泛型让 input 直接携带 HTMLInputElement 的属性;files 是 FileList | null
const file = input.files?.[0];
if (file) {
console.log('picked:', file.name, file.type, file.size, 'bytes');
} else {
console.log('selection cleared');
}
});

Interactive Tools for This Topic

FAQ

Does querySelector Generic Types File Input run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.