Typing Function Parameters
Give each parameter a type so callers pass the right arguments.
Syntax
function add(a: number, b: number) { }Function parameters are typed the same way as variables — with a colon and a type. TypeScript then checks every call site to ensure the arguments match.
Parameter types are one place you almost always write explicit annotations, since TypeScript cannot infer them from the function body.
Example
Loading editor…
Press Run to execute the code.
When to use it
- An HTTP handler function annotates its request and response parameters so the implementation can safely call methods on them.
- A calculation utility types both input parameters as number so string inputs are caught before the function runs.
- A rendering function that accepts a DOM element parameter gets HTMLElement as its type, enabling IDE method autocomplete.
More examples
Parameters with type annotations
Annotates both parameters as string so passing a number is caught immediately at the call site.
function greet(firstName: string, lastName: string): string {
return `Hello, ${firstName} ${lastName}!`;
}
greet('Alice', 'Smith'); // OK
greet('Alice', 42); // Error: Argument of type 'number' is not assignableMultiple parameter types
Uses all three primitive types across three parameters, demonstrating mixed-type function signatures.
function createPost(title: string, views: number, published: boolean): string {
const state = published ? 'live' : 'draft';
return `"${title}" — ${views} views [${state}]`;
}Object parameter type
Accepts an interface-typed parameter, enabling property-level autocomplete and type checking inside the function.
interface OrderItem {
sku: string;
qty: number;
price: number;
}
function lineTotal(item: OrderItem): number {
return item.qty * item.price;
}
console.log(lineTotal({ sku: 'PEN-01', qty: 5, price: 1.99 }));
Discussion