Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

Import in declaration files not recognized as module

I'm extracting all typescript interfaces from my current application to a npm package since I'm building a microservice architecture that will use the same interfaces and enums.

The issue I'm having is that some of the interfaces needs third party types which I'm trying to import into my declaration type but it's throwing an error.

Cannot use import statement outside a module

I'm not getting any warnings while typing, but when uploading the changes and updating the npm package in my actual application.

This is a stripped version of my index.d.ts

import { ObjectId } from 'mongodb'
    
declare module MyApp {
  export interface MyInterface {
    _id: ObjectId
    firstName: string
    lastName: string
    ...
  }
}

And this is my tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

I've tried

declare module MyApp {
  import { ObjectId } from 'mongodb'

  export interface MyInterface {
    ...

Which gives me

Import declarations in a namespace cannot reference a module

I've also tried

import { ObjectId } from 'mongodb'

export interface MyInterface {
  ...

But nothing happens. I've tried changing declare module to declare namespace. Nothing happens.

I've tried both with and without "type": "module" in my package.json, nothing happens.

Upvotes: 0

Views: 1086

Answers (1)

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

So everyhing was correctly configured it seems. It was a faulty import inside my application.

This was the fix

// Old
import MyApp from '@org/my-app'

// Fix
import { MyApp } from '@org/my-app'

Which broke when i tried to access anything inside the declaration file with MyApp.MyInterface.

Upvotes: 1

Related Questions