Function Parameter Types
In this page:
Basic Parameter Types
Add a type after each parameter name, like (name: string), to specify exactly what kind of value that parameter should receive. This turns a plain JavaScript function into one where the compiler actively verifies every call site.
Example: Basic Parameter Types
function greet(name: string) {
console.log(`Hello, ${name}`);
}
greet("Dev");
Multiple Parameters
Each function parameter can carry its own independent type annotation, so a function can mix a string, a number, and a boolean parameter in a single signature. TypeScript checks each argument against its corresponding parameter's type separately.
Example: Multiple Parameters
function createUser(name: string, age: number, active: boolean) {
console.log(name, age, active);
}
createUser("Isha", 25, true);
Boolean Parameters
Boolean parameters are useful whenever a function needs a simple true-or-false decision, such as a flag controlling whether to include extra output. Typing it as boolean rules out accidentally passing a truthy string like "yes" instead of an actual boolean.
Example: Boolean Parameters
function printReport(includeDetails: boolean) {
console.log(includeDetails ? "Full report" : "Summary only");
}
printReport(true);
Object Parameters
Function parameters can also describe the structure of an object passed to the function, either inline or via a named interface. This documents exactly which properties the function expects to find on that argument, and catches a missing or misspelled property immediately.
Example: Object Parameters
function printUser(user: { name: string; age: number }) {
console.log(user.name, user.age);
}
printUser({ name: "Rohan", age: 30 });
Why Parameter Types Matter
Parameter types make functions considerably safer by documenting the expected shape of every input directly in the signature. They let TypeScript detect an incorrect call, like passing arguments in the wrong order or of the wrong kind, before the code ever runs.
Example: Why Parameter Types Matter
function multiply(a: number, b: number) {
return a * b;
}
// multiply("2", 3); // rejected: caught before running
console.log(multiply(2, 3));
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: