

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
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:
// Error: Required parameter cannot follow optional parameter
function greet(title?: string, name: string): string {
// ...
}
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.
0.10pro tier is specified, each request costs 0.05enterprise tier is specified, each request costs 0.03