Function Signatures
Define function signatures to describe the shape of a function — its parameters and return type.
Function Signatures
A function signature describes what a function looks like — its parameter types and return type — without implementing it.
Basic Function Signature
let greet: (name: string, greeting: string) => void;
greet = (name: string, greeting: string) => {
console.log(`${greeting}, ${name}`);
};
Signature with Return Type
let calc: (a: number, b: number, action: string) => number;
calc = (a: number, b: number, action: string) => {
if (action === "add") return a + b;
if (action === "subtract") return a - b;
return 0;
};
Signatures with Objects
type Person = { name: string; age: number };
let logDetails: (obj: Person) => void;
logDetails = (ninja: Person) => {
console.log(`${ninja.name} is ${ninja.age}`);
};
Using Type Aliases for Signatures
type MathFunc = (a: number, b: number) => number;
const add: MathFunc = (a, b) => a + b;
const subtract: MathFunc = (a, b) => a - b;
Key Takeaways
- Function signatures define parameter and return types
- The implementation must match the signature
- Use type aliases for reusable function signatures
- Great for callbacks and function parameters