How to useDefault Parameter Values in Typescript
In TypeScript, you can utilize default parameter values to specify optional properties within functions or constructors. This approach can be particularly useful when you need optional properties within function parameters or constructor arguments.
- Specify default parameter values for optional properties within functions or constructors.
- Utilize the defined default parameter values to handle optional properties within functions or constructors.
Example: In this example we are following above explained approach.
// Define a function with optional properties using default parameter values
function createUser(name: string, age: number, designation: string = 'Employee') {
return {
name,
age,
designation,
};
}
// Create users with different optional properties
const user1 = createUser('GFG', 23);
const user2 = createUser('Nikunj', 22, 'Developer');
console.log(user1);
console.log(user2);
Output:
{ name: 'GFG', age: 23, designation: 'Employee' }
{ name: 'Nikunj', age: 22, designation: 'Developer' }
TypeScript Optional Properties Type
TypeScript Opional properties type provides a way of defining the parts that are not necessarily required.