Parameter Typing, Return Types, and Modern Syntax
Learn how to define and use functions in TypeScript with proper typing. This module explains function parameter typing, return types, optional and default parameters, and arrow functions with clear, real-world examples.
1. Function Parameter Typing
In TypeScript, function parameters are strongly typed. This ensures that functions receive the correct type of input and prevents runtime errors.
Example
If a value of an incorrect type is passed, TypeScript produces a compile-time error.
Why Parameter Typing Is Important
Parameter typing improves code reliability, readability, and collaboration in team-based projects.
2. Return Types
Return types define the type of value a function returns. Although TypeScript can infer return types, explicitly specifying them is recommended for clarity and maintainability.
Example
Void Return Type
The void return type is used when a function does not return any value.
3. Optional Parameters
Optional parameters allow a function to accept fewer arguments. They are marked using a question mark and must be placed after required parameters.
Example
Valid Function Calls
Optional parameters are commonly used when values are not always required.
4. Default Parameters
Default parameters assign a default value to a parameter when no value is provided during the function call.
Example
If the discount parameter is omitted, the function uses the default value.
5. Arrow Functions
Arrow functions provide a concise syntax and automatically bind the this keyword, making them ideal for callbacks and modern frameworks.
Basic Arrow Function
Short Form Arrow Function
Arrow functions are widely used in React, Angular, and Node.js applications.
Conclusion
Functions in TypeScript provide strong type safety and clarity compared to JavaScript. By using typed parameters, defined return types, optional and default parameters, and arrow functions, developers can build reliable and maintainable applications.