Course contentsShow
← TypeScript
Lesson 1155 of 1,79627. Declaration FilesFree lesson

Wildcard Module Declarations

Use declare module '*.css' or '*.svg' to type-check imports for non-JS assets in bundlers.

Wildcard Module Declarations

What you'll learn: How to use declare module '*.css' or declare module '*.svg' to type-check imports for non-JavaScript assets in bundlers.

What Are Wildcard Module Declarations?

Modern build tools like Webpack, Vite, and Parcel let you import files that aren't JavaScript or TypeScript—CSS files, images, SVGs, JSON, and more. But TypeScript doesn't know these file types exist, so it throws errors when you try to import them.

Wildcard module declarations solve this by telling TypeScript: "Any module whose path matches this pattern should have this type." You use the declare module syntax with a glob pattern containing a * wildcard.

Basic Syntax

Here's how you tell TypeScript that CSS imports are valid:

declare module '*.css' {
  const content: { [className: string]: string };
  export default content;
}

Now when you write import styles from './Button.css', TypeScript knows styles is an object with string keys and values, instead of throwing "Cannot find module './Button.css'."

Common Wildcard Patterns

For SVG files imported as React components:

declare module '*.svg' {
  const content: string;
  export default content;
}

For image files that return URLs:

declare module '*.png' {
  const value: string;
  export default value;
}

Where to Put These Declarations

Create a file like src/types/modules.d.ts (any .d.ts file that TypeScript finds will work). Make sure it's included in your tsconfig.json compilation.

Analogy

Think of wildcard module declarations like creating a universal translator. Your bundler speaks "CSS" and "SVG," but TypeScript only speaks "JavaScript/TypeScript." The wildcard declaration is a phrasebook that says: "When you see anything ending in .css, treat it like this type of JavaScript object."

Key Takeaway: Wildcard module declarations use declare module '*.extension' to provide types for non-JavaScript assets that bundlers can import, preventing TypeScript errors and enabling type-safe usage of these resources.