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

Declaring Global Functions

Type global functions with declare function to describe APIs provided by the environment.

Declaring Global Functions

What you'll learn: How to type global functions with declare function so TypeScript understands APIs provided by the browser or runtime environment.

The Problem: Runtime Functions TypeScript Doesn't Know About

Sometimes you're working in an environment that provides global functions—like a browser API you've added via a <script> tag, or a custom runtime with built-in utilities. TypeScript doesn't automatically know these exist.

You've already learned declare creates ambient declarations (promises that something exists at runtime). Now you'll use declare function to tell TypeScript about global functions.

The declare function Syntax

// Tell TypeScript: "Trust me, there's a global myCustomAlert function"
declare function myCustomAlert(message: string): void;

// Now you can call it with type safety
myCustomAlert("Hello!"); // ✓ OK
myCustomAlert(123);      // ✗ Error: Argument of type 'number' not assignable

This doesn't create the function—it just describes it for the type checker.

Real-World Example: Browser Extensions

Imagine a browser extension that injects a global function:

// In your .d.ts file
declare function logToExtension(level: string, message: string): void;

// In your code
logToExtension("info", "User logged in"); // ✓ Typed and checked

Think of It As Documentation for the Type System

declare function is like telling TypeScript: "This function will exist at runtime—here's its signature so you can check my usage." You're not implementing it; you're documenting the contract.

Key Takeaway: Use declare function to type global functions provided by your environment, giving you autocomplete and type safety without creating runtime code.