How to Fix the Cannot Use Namespace as a Type Error in TypeScript

Last updated on September 29, 2022
How to Fix the Cannot Use Namespace as a Type Error in TypeScript

Are you experiencing the "cannot use namespace as a type" error in TypeScript?

This error can occur when you try to import types declared as a module. For example:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
}

index.ts


import Car from 'car';

// Cannot use namespace 'Car' as a type.
const user: Car = {
  color: 'red',
  age: 2,
  maxSpeed: 120,
};

To fix this error, use an export assignment to specify a default export for the namespace, like this:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
  export = Car;
}
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also