I've been grappling with this problem for the past few days, scouring the internet and reading extensively, but I haven't come across any examples that match my specific scenario. My goal is to publish a library using npm
that includes its own type definitions.
I recently delved into TypeScript because other teams require my library to support typings.
Here's an overview of what I have so far:
tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowUmdGlobalAccess": true,
"baseUrl": ".",
"declaration": true,
"declarationMap": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"module": "commonjs",
"noImplicitAny": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"outDir": "./dist/",
"paths": {
},
"sourceMap": true,
"strict": true,
"target": "es6",
},
"include": [
"./src"
]
}
package.json:
"main": "dist/index.js",
"scripts": {
"tsc": "tsc",
"prepack": "npm run clean && npm run tsc",
},
"types": "./dist/index.d.ts",
src/index.ts (built into dist/index.js + dist/index.d.ts):
export { IAction, IState } from './types';
src/types (built into dist/types.js + dist/types.d.ts):
import { Map } from 'immutable';
export interface IAction {
type: string;
payload: object;
}
export interface IState extends Map<string, Map<string, any>> {
}
I have additional code in this repository that successfully uses these interfaces. The TypeScript compiler doesn't raise any issues during the build process.
Currently, I package the library by running npm pack
and then install it in another project using
npm install ../path/to/my/file-0.0.1.tgz
. When attempting to use my interfaces (such as in a Redux reducer), like so:
import { IAction, IState } from 'my-lib'; // <-- matching package name specified in package.json
const reducer = (state: IState, action: IAction) => {
...
}
However, I'm encountering the following errors:
error TS2709: Cannot use namespace 'IState' as a type.
error TS2709: Cannot use namespace 'IAction' as a type.
I'm struggling to understand why this error occurs. Is there an additional step I need to take to generate my definition file automatically? Ideally, I'd prefer not to create it manually.
If you require further details, please let me know.
Thank you for your assistance and patience in reviewing this information.