skip to Main Content

I have my own JS library and I add there declaration files (*.d.ts) for my TS projects which use that JS library. There’s something wrong and my TS project ignore that declaration files.


So I tried this stupid example in my TS project.

// project/src/calculateSum.js

function calculateSum(a, b) {
  return a + b
}

module.exports = {
  calculateSum
}
// project/src/types/custom/calculateSum.d.ts

export declare function calculateSum(a: number, b: number): number;
// project/src/app.ts

import { calculateSum } from './calculateSum`

console.log(calculateSum('it should not acceept string', 1))

VS code and TS does not report anny issue with that.

Here my tsconfig.json

{
  "compilerOptions": {
    ...
    "skipLibCheck": true,
      "typeRoots": [
        "node_modules/@types",
        "src/types/custom"
      ]
  },
  "include": [
    "./src/**/*",
  ],
    "exclude": [
      "node_modules"
    ]
}

BTW I have also svg.d.ts inside src/types/custom and it works as expected.

// project/src/types/custom/svg.d.ts
declare module "*.svg" {
    import React = require("react")
    export const AsComponent: React.FC<React.SVGProps<SVGSVGElement>>
    const src: string
    export default src
}

It seems to me that I misunderstood something.

2

Answers


  1. As far as I know, the type definitions for your .js files should be in the same folder for it to work, since you can have multiple definition files with the same function declared in each.

    Your svg.d.ts works as expected, probably because that’s a general definition for all *.svg imports (I think).

    Also, check this answer on a similar topic out: https://stackoverflow.com/a/44060120/15076557

    Login or Signup to reply.
  2. You can make it work by adding in your tsconfig.json :

    "compilerOptions": {
      ...
      "rootDirs": ["src", "src/types/custom"],
      ...
    }
    

    TS documentation

    Using rootDirs, you can inform the compiler that there are many “virtual” directories acting as a single root. This allows the compiler to resolve relative module imports within these “virtual” directories, as if they were merged in to one directory.

    I would also remove the whole "typeRoots" field from your tsconfig.json : you should not need it anymore.

    Note : I presume you also need "allowJs": true, or else the tsc compiler will not emit your .js files.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search