TypeScript Functions
Functions are the fundamental building blocks of any application, used to perform specific tasks. In TypeScript, we can add types to function parameters and return values, making functions more robust and easier to understand.
Defining Functions
You can create functions using function declarations or function expressions.
Function Declaration
Function Expression
Function Types
We can define a function type for a variable, so it can only hold a function that matches that type.
Parameter Types
1. Type Annotation and Type Inference
As shown in the examples above, you can add type annotations to function parameters. The return value type can also be annotated. If you omit the return type annotation, TypeScript will try to infer it based on the return statements.
2. Optional Parameters
In TypeScript, every function parameter is considered required. However, you can mark a parameter as optional by using ? after the parameter name.
Optional parameters must come after required parameters.
3. Default Parameters
You can set a default value for a parameter. When the user doesn't provide that parameter or provides undefined, the parameter will use the default value.
Unlike optional parameters, parameters with default values don't have to come after required parameters.
4. Rest Parameters
If you need to handle multiple parameters as a group, or you don't know how many parameters a function will ultimately receive, you can use rest parameters. They are collected into an array.
Arrow Functions
Arrow functions are a more concise function syntax introduced in ES6. They also solve the issue of how the this keyword behaves in traditional functions.
Syntax
Behavior of this
In arrow functions, the value of this is determined by the context where the function is created, not where it's called. This is very useful when handling event handlers or callback functions.
If start were a regular function, this in the setInterval callback would be window (in browsers) or undefined (in strict mode), causing this.value to error.