1

Im not sure why but typescript cannot find my declaration file even though I have one. Can anyone see why this is?

My project structure:

scr
  - main.ts
  - dec.d.ts

str-utils
  - index.js

The import:

import {strReverse, strToLower} from '../str-utils/index.js' 

My declaration file (dec.d.ts):

declare module "str-utils"

My typescript config:

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": false,
    "outDir": "dist"
  },
  "include": [
    "src/**/*",
    "src/dec.d.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Can anyone see what I am doing wrong here?

1 Answer 1

1

The general rule for the name of declare module "{name}" is that it should be the same name you would use to import the module. So, in this case, declare module '../str-utils/index.js'. But this will not work because declare module "{name}" doesn't work for relative paths. You have two options to solve this issue:

1. Making the import non-relative:

You modify the tsconfig to make str-utils available without a relative import.

{
  "compilerOptions": {
    // other options
    "paths": {
      "string-utils": ["./str-utils/index.js"]
    },
  },
  // other options
}

Now you can import str-utils via import {strReverse, strToLower} from 'str-utils' and thus, your module declaration works.

2. Moving the declaration file into the str-utils folder

First, you need to remove declare module "str-utils" from your declaration file. It should look something like this:

// no wrapping declare module "name" anymore
export function strReverse(arg: string): string;

export function strToLower(arg: string): string;

Then you need to rename the declaration file name to match the file name of the module you want to augment. In this example, we want to augment index.js, so the type declaration's file name should be index.d.ts. Your folder structure should look like that for this approach:

src
  - main.ts
  
str-utils
  - index.d.ts
  - index.js
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.