Setting Default Values in TypeScript
Sometimes it is wise to stick to default values for parameters in TypeScript / JavaScript functions. I mainly use two approaches in my daily life to handle this.
- Using Default Parameters
- Object Destruction with Default values
Using Default Parameters
interface Superhero {
name?: string;
skill?: string;
isSmart?: boolean;
}
const defaultSuperhero: Superhero = {
name: 'Unknown Hero',
skill: 'Unknown Skill',
isSmart: false,
};
function describeSuperhero(superhero: Superhero = defaultSuperhero): void {
const { name, skill, isSmart } = superhero;
console.log(`Superhero: ${name}. Skill: ${skill}. Smart: ${isSmart}`);
}
// Example usage:
describeSuperhero(); // Output: Superhero: Unknown Hero. Skill: Unknown Skill. Smart: false
describeSuperhero({ name: 'Spider-Man', skill: 'Web-Slinging' }); // Output: Superhero: Spider-Man. Skill: Web-Slinging. Smart: falseWe define a default Superhero object (defaultSuperhero) and use it as the default parameter for the describeSuperhero function. If no arguments are passed to the function, it uses the defaultSuperhero values.
Object Destruction with Default values
interface Superhero {
name?: string;
skill?: string;
isSmart?: boolean;
}
function describeSuperhero({ name = 'Unknown Hero', skill = 'Unknown Skill', isSmart = false }: Superhero): void {
console.log(`Superhero: ${name}. Skill: ${skill}. Smart: ${isSmart}`);
}
// Example usage:
describeSuperhero({}); // Output: Superhero: Unknown Hero. Skill: Unknown Skill. Smart: false
describeSuperhero({ name: 'Spider-Man', skill: 'Web-Slinging' }); // Output: Superhero: Spider-Man. Skill: Web-Slinging. Smart: falseWe use object destructuring with default values directly in the function parameter list. This method allows each property to have a default value, which is used if the corresponding property is not provided in the argument object.
Get rare.’s stories in your inbox
Join Medium for free to get updates from this writer.
The destructuring approach looks smoother I think and it is often used in React for example.









