in my TypeScript code I want to include a NPM JavaScript module for which there are no typings.
import createPersist = require('vuex-localstorage');
Because of that the compiler complains:
error TS7016: Could not find a declaration file for module 'vuex-localstorage'. '<path>\node_modules\vuex-localstorage\dist\index.js' implicitly has an 'any' type.
One possibility to solve this is setting "noImplicitAny"
to false
in my tsconfig.json
. But this I do not want. I want to know what is not typechecked any more.
So I wrote a minimal type declaration for vuex-localstorage
which I put in my project directory:
interface PersistOptions {
namespace?: string;
initialState?: any;
provider?: any;
serialize?: (data:any) => string;
deserialize?: (str:string) => any;
expires?: number;
merge?: (args:any[]) => any;
reducer?: (state:any, paths:string[]) => any;
paths?: string[];
}
declare function createPersist(options: PersistOptions): any;
export = createPersist;
However I still have the same error. I tried several things to get the TypeScript compiler to recognize my type declaration file but nothing worked.
So how do I do it?
Just create a file named typings. d. ts in the root directory of your project. Inside this file just add declare module <module_name> .
All the type declarations that is added via DefinitelyTyped / @types will be saved under node_modules/@types/<package-name> folder. TypeScript will automatically detect these declaration files and infer the type from it.
You can use npm to install TypeScript globally, this means that you can use the tsc command anywhere in your terminal. To do this, run npm install -g typescript . This will install the latest version (currently 4.8). An alternative is to use npx when you have to run tsc for one-off occasions.
Declaration files, if you're not familiar, are just files that describe the shape of an existing JavaScript codebase to TypeScript. By using declaration files (also called . d. ts files), you can avoid misusing libraries and get things like completions in your editor.
you need to help the compiler know that what you wrote is for that module.
Try this:
declare module 'vuex-localstorage' {
interface PersistOptions {
namespace?: string;
initialState?: any;
provider?: any;
serialize?: (data: any) => string;
deserialize?: (str: string) => any;
expires?: number;
merge?: (args: any[]) => any;
reducer?: (state: any, paths: string[]) => any;
paths?: string[];
}
function createPersist(options: PersistOptions): any;
export = createPersist;
}
Don't forget to make sure that this declaration file gets included in tsconfig.json.
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