Function Type Syntax
What
Function type syntax allows you to define the expected types for both the inputs (parameters) and the output (return value) of a function.
How
You add a : followed by the type after each parameter name, and another : followed by the type after the parameter list:
// Standard Function
function createMessage(name: string, score: number): string {
return `${name} scored ${score}`;
}
// Arrow Function
const createMessage = (name: string, score: number): string => {
return `${name} scored ${score}`;
};
Why
Typing functions ensures that they are called with the correct arguments and that the values they return are used correctly elsewhere in your application. This prevents a common class of runtime errors where functions receive undefined or incorrect data types.
Summary
Explicit function signatures are one of the most effective ways to document and secure the logic within your codebase.