Course contentsShow
← TypeScript
Lesson 1622 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Third-Party Libraries Without Types

Strategies for handling npm packages that lack TypeScript definitions or DefinitelyTyped entries.

Third-Party Libraries Without Types

You'll learn how to safely integrate npm packages that lack TypeScript definitions into your migration.

The Problem

During your JavaScript-to-TypeScript migration, you'll inevitably encounter third-party packages that don't provide type definitions—neither bundled with the package nor available through DefinitelyTyped's @types/* ecosystem. These packages become black holes in your type system, forcing TypeScript to treat them as any and breaking your type safety chain.

This is especially common with:

  • Legacy or unmaintained packages
  • Niche utility libraries
  • Recently published packages without types yet
  • Internal company packages migrated from JavaScript

Strategy 1: Create Local Declaration Files

The most maintainable approach is writing minimal .d.ts files for the specific APIs you actually use:

// types/old-validator.d.ts
declare module 'old-validator' {
  export function isEmail(value: string): boolean;
  export function sanitize(input: string): string;
}

// Now you can import safely:
// import { isEmail } from 'old-validator';

You only need to declare what you're actually calling—not the entire API surface.

Strategy 2: The any Escape Hatch

When you need the package immediately and don't know its shape, create a permissive wildcard declaration:

// types/mystery-package.d.ts
declare module 'mystery-package';

// Allows imports but everything becomes 'any'
// import stuff from 'mystery-package'; // stuff: any

This unblocks migration but sacrifices type safety—document that you'll need to improve this later.

Strategy 3: unknown and Type Guards

For critical code paths, import with any but immediately narrow to unknown and validate:

// Import the untyped library
import * as untypedLib from 'old-library';

function processData(input: string): number {
  const result = (untypedLib as any).transform(input) as unknown;
  
  if (typeof result === 'number') {
    return result;
  }
  throw new Error('Unexpected result type');
}

This adds runtime safety where type safety isn't available.

Choosing Your Strategy

Use local declaration files when you understand the API and plan to use it extensively. Use wildcard declarations for temporary unblocking during migration. Use unknown with guards when the data flows through critical business logic that needs runtime validation.

Key Takeaway: Third-party packages without types don't have to derail your migration—create minimal local declarations for what you actually use, accept temporary any wildcards for low-risk code, and add runtime validation for critical paths.