Error Codes Wiki

TypeScript Browser Errors — Type Errors, Module Resolution, and DOM Type Issues

Warningweb development

Overview

Fix TypeScript errors in browser applications including DOM type assertions, module resolution failures, and lib configuration for browser APIs.

Key Details

  • TypeScript requires type definitions for browser APIs — configured via lib option in tsconfig.json
  • DOM elements returned by querySelector are typed as Element | null — type narrowing is required
  • Module resolution (node, bundler, nodenext) affects how imports are resolved
  • Missing type definitions for third-party libraries cause 'Could not find a declaration file' errors
  • Strict mode (strict: true) enables all strict type checking options and catches more errors

Common Causes

  • tsconfig.json missing 'dom' in lib array — browser APIs like document and window are unrecognized
  • querySelector returning Element | null not narrowed before use
  • Third-party library missing @types/ package for TypeScript type definitions
  • Module resolution strategy not matching the bundler (Webpack, Vite, esbuild) configuration

Steps

  1. 1Add DOM types: set 'lib': ['ES2020', 'DOM', 'DOM.Iterable'] in tsconfig.json
  2. 2Narrow DOM types: use type guards — if (el instanceof HTMLInputElement) { el.value = 'text'; }
  3. 3Install type definitions: 'npm install -D @types/library-name' for untyped libraries
  4. 4Set module resolution: 'moduleResolution': 'bundler' for Vite/modern bundlers, 'node' for Webpack 4
  5. 5Use non-null assertion (el!) sparingly — prefer proper null checking with if statements

Tags

typescriptbrowserdomtypesmodule-resolution

More in Web Development

Frequently Asked Questions

The 'dom' lib is not included in tsconfig.json. Add '"lib": ["ES2020", "DOM", "DOM.Iterable"]' to compilerOptions. Without it, TypeScript only knows Node.js types.