Simple Function Implementation
The initial implementation of the function, namedmakeDuckQuack, logs a duck’s quack message. This function accepts a duck object and an optional parameter to specify the number of quacks. If the optional parameter is omitted, the duck quacks once by default.
- The first parameter is a duck object.
- The second parameter,
times, determines how many times the duck will quack.
Experimenting with Type Definitions
During development, a type definition for the duck and an example duck object were introduced. An incomplete function implementation caused compilation errors. Below is the snippet that initially led to errors:These errors occur due to an incomplete implementation of the function. Always ensure your function implementations are complete to avoid compilation issues.
Corrected Implementation
Below is the corrected version of the code with proper error handling and structure:Using Default Parameter Values
We can simplify the function by using a default parameter value. This approach removes the need for the optional marker and manually setting a default value inside the function. Consider the following revised version:yarn dev, you’ll see:
times parameter (i.e., makeDuckQuack(daffy)) will result in a single quack by default.
Function Styles in TypeScript
Another common way to define functions in TypeScript is by using arrow functions. Both traditional function declarations and arrow functions are valid. Below are examples of each style:Traditional Function Declaration
Arrow Function Expression
Complete Working Example
Here’s a complete example using the simplified default parameter syntax:-
For
makeDuckQuack(daffy): -
For
makeDuckQuack(daffy, 2):
