Third-Party Libraries Without Types
What you'll learn: How to safely use JavaScript libraries that lack TypeScript definitions by asserting their types when you know the shape but TypeScript doesn't.
The Problem: Untyped JavaScript in a Typed World
Not every JavaScript library has TypeScript types. Sometimes you'll install a package and find TypeScript has no idea what shape its exports have. TypeScript treats these as any (or errors if you have noImplicitAny enabled), which defeats the purpose of type safety.
But here's the thing: you often know what shape the library returns from reading its documentation. You just need to tell TypeScript what you know.
Type Assertions to the Rescue
This is where type assertions become legitimate. When TypeScript can't infer types from an external library, you can assert the shape explicitly using as:
// Imagine 'old-cool-lib' has no types available
import coolLib from 'old-cool-lib';
// TypeScript sees this as 'any' - not helpful!
// But YOU know from the docs it returns { doThing: (x: number) => string }
interface CoolLibAPI {
doThing: (x: number) => string;
version: string;
}
const lib = coolLib as CoolLibAPI;
// Now you have autocomplete and safety!
const result = lib.doThing(42); // TypeScript knows this returns string
Creating Your Own Declaration Files
For libraries you use frequently, you can create a .d.ts file to declare the module's shape once:
// types/old-cool-lib.d.ts
declare module 'old-cool-lib' {
export interface CoolLibAPI {
doThing: (x: number) => string;
version: string;
}
const coolLib: CoolLibAPI;
export default coolLib;
}
Now TypeScript knows the shape everywhere you import it—no assertions needed at every call site.
Key Takeaway: When third-party libraries lack TypeScript definitions, use type assertions (or declaration files) to teach TypeScript the shapes you've learned from documentation—you're bridging the gap between what you know and what the compiler can infer.