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
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
You can make it work by adding in your tsconfig.json :
TS documentation
I would also remove the whole
"typeRoots"
field from yourtsconfig.json
: you should not need it anymore.Note : I presume you also need
"allowJs": true
, or else thetsc
compiler will not emit your.js
files.