Default Values

Often a missing argument has an obvious value. When Kira attacks without anything special, she hits with a power of 10. With an optional parameter, you'd have to check for undefined yourself. A default value is shorter, and you know it from JavaScript:

function attack(monster: string, power: number = 10): string {
    return `Kira hits the ${monster} with power ${power}`;
}

console.log(attack("goblin"));
console.log(attack("troll", 25));

This prints:

Kira hits the goblin with power 10
Kira hits the troll with power 25

A parameter with a default value is optional too: the call may leave it out. Unlike power?: number, though, it's never undefined inside the function. When the argument is missing, power is 10. So its type inside the function is simply number, and you can compute with it without any check.

You can even leave out the type. From power = 10, TypeScript works out that power is a number, just as with let power = 10;. You'll see both forms in real code. The calls are checked either way:

function attack(monster: string, power = 10): string {
    return `Kira hits the ${monster} with power ${power}`;
}

console.log(attack("wolf", "big"));
main.ts(5,28): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

And the default value itself must fit the type: power: number = "10" gives Type 'string' is not assignable to type 'number'.

Which one to choose? A default value, when there is a value that fits most calls. An optional parameter with ?, when a missing value means something different, as with the guest without a title in the previous exercise, who is welcomed with a different text.

Typical mistakes:

  • A question mark and a default value together: power?: number = 10 gives Parameter cannot have question mark and initializer. The default value already makes the parameter optional, so leave out the ?.
  • Parameters with default values before the required ones. With function attack(power = 10, monster: string), the call attack("goblin") gives Expected 2 arguments, but got 1. Arguments go into parameters in order, so put the parameters with default values at the end.

Instructions

Most guests drink water with their meal. Give the parameter drink the default value "water".

Most guests also order a single portion. Give count the default value 1. Then, at the end of the program, print order("Bread"). The program prints:

1x Mushroom Soup with water
2x Roast Boar with cider
1x Bread with water

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10