

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Unions
incomplete
2: Optional Parameters
incomplete
3: Default Parameters
incomplete
4: Literal Types
incomplete
5: Value Unions
incomplete
6: Template Literal Types
incomplete
7: Giant Unions
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
You can specify function parameters as optional with a question mark (?) after the name:
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
greet("Gandalf"); // "Hello, Gandalf!"
greet("Gandalf", "Wizard"); // "Hello, Wizard Gandalf!"There are two rules to keep in mind:
Optional parameters must come after all required parameters. For example, this code won't compile:
// Error: Required parameter cannot follow optional parameter
function greet(title?: string, name: string): string {
// ...
}Optional params have an undefined automatically unioned on the specified type. If the value is omitted, it's undefined instead of the specified type.
function greet(name: string, title?: string): string {
// inside the function, title
// is a string | undefined
}At Support.ai, we're building a service that calculates pricing for our API usage. Different tiers of customers get different rates.
If no tier is provided, or if the tier is not recognized, each request costs 0.10
If the pro tier is specified, each request costs 0.05
If the enterprise tier is specified, each request costs 0.03