Course contentsShow
← TypeScript
Lesson 1128 of 1,79626. Modules in TypeScriptFree lesson

Wildcard Module Declarations

Typing non-code imports like CSS, images, and JSON files with wildcard module declarations.

Wildcard Module Declarations

You'll learn how to type non-code imports like CSS, images, and JSON files using wildcard patterns so TypeScript understands what happens when you import them.

What Are Wildcard Module Declarations?

When you write modern web applications, you often import more than just TypeScript or JavaScript files. You might import CSS modules, images, SVG files, or JSON data. TypeScript doesn't inherently know how to type these non-code imports.

Wildcard module declarations let you tell TypeScript: "When someone imports a file matching this pattern (like *.png), here's what type it should have."

Think of wildcards as catch-all rules for file extensions. Just like ambient module declarations let you describe modules by exact name, wildcards use the * character to match any filename with a specific ending.

The Basic Pattern

The syntax uses declare module with a string containing a * wildcard:

declare module "*.css" {
  const styles: { [key: string]: string };
  export default styles;
}

This tells TypeScript: "Any import ending in .css exports an object where keys are strings (class names) and values are strings (generated class names)."

Common Use Cases

CSS Modules:

declare module "*.module.css" {
  const classes: { readonly [key: string]: string };
  export default classes;
}

Image Files:

declare module "*.png" {
  const src: string;
  export default src;
}

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

JSON Files (though resolveJsonModule is often better):

declare module "*.json" {
  const value: any;
  export default value;
}

Why This Matters

Without these declarations, importing a CSS file would cause TypeScript to complain that it can't find a module. With wildcard declarations, you get type safety and autocomplete for non-code assets handled by your bundler (Webpack, Vite, etc.).

Key Takeaway: Wildcard module declarations bridge the gap between TypeScript's type system and your bundler's ability to import non-JavaScript assets, providing type safety for CSS, images, and other file types that TypeScript doesn't natively understand.