Course contentsShow
← TypeScript
Lesson 1139 of 1,79627. Declaration FilesFree lesson

Declaring Functions

Use declare function to describe the signature of functions implemented elsewhere in JavaScript.

Declaring Functions

What you'll learn: How to use declare function to describe JavaScript functions that TypeScript doesn't know about.

What This Solves

Sometimes your TypeScript code needs to call functions that are implemented in plain JavaScript files — perhaps legacy code, third-party scripts loaded via <script> tags, or browser globals. TypeScript has no way to see these implementations, so it doesn't know the functions exist or what types they expect.

The declare function syntax lets you tell TypeScript: "Trust me, this function exists at runtime. Here's its type signature."

Basic Syntax

In a .d.ts file (or at the top level of a .ts file), you write:

declare function functionName(param: Type): ReturnType;

Notice there's no function body — just the signature. You're not implementing the function, just declaring that it exists elsewhere.

A Practical Example

Imagine you have a legacy JavaScript file that defines:

// legacy.js (plain JavaScript, loaded separately)
function calculateTax(price, rate) {
  return price * rate;
}

In your TypeScript code, you want to call calculateTax, but TypeScript doesn't know about it. You declare it:

// types.d.ts
declare function calculateTax(price: number, rate: number): number;

Now TypeScript knows this function exists globally, and it will type-check your calls:

const total = calculateTax(100, 0.08); // ✓ Allowed
const bad = calculateTax("100", 0.08);  // ✗ Error: string not assignable to number

Where Declare Functions Live

declare function statements typically go in declaration files (.d.ts), which we covered previously. These files describe the shape of code without implementing it.

Key Takeaway: Use declare function to provide type signatures for JavaScript functions that exist at runtime but aren't visible to TypeScript's compiler — enabling type safety when calling external or legacy code.