Home > Software design >  Unable to use custom typed npm package
Unable to use custom typed npm package

Time:04-13

I've installed a package called mini-alert which doesn't have its corresponding types. I've modified the tsconfig.json to declaration but when I try to use it my code it throws this error: `Uncaught TypeError: Object(...) is not a function.

1. Handling the missing types myself

interface Props{
    overflow?: boolean;    
    autoremove?: boolean;    
    time?: number;        
    size?: string;       
    cartoon?: boolean;      
    limit?: number;            
    text?: string;
}
declare module 'mini-alert'{
    export const miniAlert: (args: Props) => void;
};

tsconfi.json setup

{
  "compilerOptions": {   
    "allowJs": true,
    "declaration": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "ES2021"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "target": "ES2021",
    "types": []
  },
  "include": [
    "src",
    "types"
  ],
  "xexclude": [
    "node_modules",
    "./node_modules",
    "./node_modules/*/*.d.ts",
    "./node_modules/@types/node/index.d.ts",
  ]
}

Using the package in my code

 const onCopyText = () => {
    setIsCopied(true);
    miniAlert({
      overflow: true, // <-- disable behind the alert
      autoremove: true, // <-- automatic remove
      time: 500, // <-- milliseconds
      size: 'large', // <-- small, medium, large
      cartoon: false, // <-- "cartoon effect" true/false
      limit: 1, // <-- max alerts visible at the same time
      text: 'Copied!'
    });   
    setTimeout(() => {
      setIsCopied(false);
    }, 1000);

Expected resul

I want to see a mini alert popup just like in this enter image description here

My use case's in a code sandbox

Codesandbox demo

CodePudding user response:

In your code sandbox you are importing mini-alert like this:

import { miniAlert } from "mini-alert";

But the documentation says to import it like this:

import miniAlert from 'mini-alert';

That means that the value you want is the default export from the package, and not a named export.

Which means the types should be something like:

declare module "mini-alert" {
  const miniAlert: (args: Props) => void;
  export default miniAlert;
}

CodePudding user response:

I typically use Vue.js rather than React, so not sure of the exact implementation, but typically if you are using a package that is JavaScript and you want to use it as TypeScript, you need to create a .d.ts file to translate the package. See the TypeScript handbook

  • Related