DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Ensuring Type Safety When Using JavaScript Libraries Without TypeScript Definitions

When working with external JavaScript libraries that don't provide TypeScript definitions, maintaining type safety in your codebase becomes challenging. Here’s how you can safely use those libraries:

  1. Use TypeScript’s declare Keyword
    • You can declare the library and its methods as any to suppress errors, but it's better to add as much detail as possible.
    • Example:
   declare module 'legacy-lib' {
     export function doSomething(param: string): number;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Write Custom Type Declarations
    • Create a *.d.ts file with more precise type information based on the library’s documentation or source code.
    • Example:
   // legacy-lib.d.ts
   declare module 'legacy-lib' {
     export function initialize(config: object): void;
     export function shutdown(): void;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use Type Assertions When Necessary
    • If you know the type of a result, but TypeScript can't infer it, use type assertions.
    • Example:
   const lib = require('legacy-lib') as {
     doSomething: (param: string) => number
   };
   const result = lib.doSomething('input');
Enter fullscreen mode Exit fullscreen mode
  1. Search for Community Types

    • Sometimes, the type definitions exist under @types/<library> on npm.
    • Example:
      • Install types using: npm install --save-dev @types/legacy-lib
  2. Use any as a Last Resort

    • Avoid using any for entire libraries unless absolutely unavoidable, as this defeats the purpose of TypeScript.

Best Practice: Always incrementally improve your custom typings as you use more of the library.

Summary of Approach

  • Create custom .d.ts files when types do not exist
  • Prefer explicit type definitions to any
  • Regularly update types as usage evolves

By carefully declaring types and updating them, you ensure your TypeScript project remains robust even when using untyped libraries.

Top comments (0)