I'm building a typescript project and using a non-typescript lib call 'draggabilly';
So I'm trying to declare it by myself.
Here is the file structure:
├── @types
│ └── draggabilly
│ └──index.d.ts
├── node_modules
├── package.json
├── README.md
├── src
│ ├── index.ts
│ └── application.ts
└── tsconfig.json
src/application.ts
import * as Draggabilly from 'draggabilly';
new Draggabilly('#dragItem', {
// options...
});
......
it's showing that
Could not find a declaration file for module 'draggabilly'. '/node_modules/draggabilly/draggabilly.js' implicitly has an 'any' type.
So I try to create the local declaration file: @types/draggabilly/index.d.ts:
export as namespace draggabilly;
export = Draggabilly;
declare class Draggabilly {
constructor(selector: string, options: any);
}
then include the types path in tsconfig.json:
{
"compilerOptions": {
......
"typeRoots": [
"./node_modules/@types",
"./@types"
]
}
}
But the error still there. So I want to know what's wrong here and what's the correct way to build the third party module declare file locally
I created a demonstration repository for this question on github: https://github.com/ZheFeng/test-ts-types
The issue is not only about how we define inside the .d.ts file, but also the typescript could not find a declaration file at all.
We can declare a module by using the export keyword. The syntax for the module declaration is given below. We can use the declare module in other files by using an import keyword, which looks like below. The file/module name is specified without an extension.
Just create a file named typings. d. ts in the root directory of your project. Inside this file just add declare module <module_name> .
To get the JavaScript files for the TypeScript modules, we need to compile modules using TypeScript compiler. Compilation of a module depends on the target environment you are aiming for. The TypeScript compiler generates the JavaScript code based on the module target option specified during compilation.
The problem is in the line export = Draggabilly;
-- you have to use the TypeScript-specific syntax import let = require("module")
to import it:
From the TypeScript documentation:
When importing a module using export =, TypeScript-specific
import let = require("module")
must be used to import the module.
So your import should be:
import Draggabilly = require("draggabilly");
index.d.ts
like below:
export as namespace draggabilly;
export class Draggabilly {
constructor(selector: string, options: any);
}
... and import it like this:
import * as draggabilly from 'draggabilly';
new draggabilly.Draggabilly('#dragItem', {
// options...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With