Sitemap
rare.

rare.

I'm Rare, a stripe-shirt aficionado and coding enthusiast. My articles mix quirky fashion with tech tips – a unique blend that's all me!

Setting Default Values in TypeScript

2 min readMay 14, 2024

--

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.

Press enter or click to view image in full size
Lots of little default values to pick from.
  1. Using Default Parameters
  2. 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: false

We 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: false

We 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.

--

--

rare.
rare.

I'm Rare, a stripe-shirt aficionado and coding enthusiast. My articles mix quirky fashion with tech tips – a unique blend that's all me!