

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: Object Literal Types
incomplete
2: Extra Properties
incomplete
3: Optional Object Properties
incomplete
4: Empty Object Type
incomplete
5: Discriminated Unions
incomplete
6: Sets
incomplete
7: Maps
incomplete
8: Dynamic Keys
incomplete
9: Dynamic Default Properties
incomplete
10: PropertyKey
incomplete
11: Readonly Modifier
incomplete
12: 'As Const' and Object.freeze
incomplete
13: Satisfies
incomplete
14: Function Overloads
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
JavaScript is very lenient when it comes to function signatures, and TypeScript gives us a way to take advantage of that flexibility while still maintaining type safety: function overloads.
First, we define a function that can be called in multiple ways:
function formatEmployeeMessage(
employee: Employee,
isNew?: boolean,
onBoardedDate?: Date,
): string {
if (!isNew) {
return `Employee: ${employee.name}, Dept: ${employee.dept}`;
}
return `Employee: ${employee.name}, New: Yes, Onboarded: ${onBoardedDate}`;
}
type Employee = {
name: string;
dept: string;
};
Used as-is, this function can be called in 3 different ways:
formatEmployeeMessage(employee)formatEmployeeMessage(employee, boolean)formatEmployeeMessage(employee, boolean, Date)But we can constrain the function to only allow certain combinations of parameters by using function overloads.
// note: function overloads need to be declared above the implementation
function formatEmployeeMessage(employee: Employee): string;
function formatEmployeeMessage(
employee: Employee,
isNew: true,
onBoardedDate: Date,
): string;
Now, it's impossible to call formatEmployeeMessage(employee, boolean) without also passing in a date. Basically we're saying, "If the employee is new, you must also pass in a date". This works:
const employee: Employee = { name: "Joe Exotic", dept: "Zoo" };
const msg = formatEmployeeMessage(employee);
console.log(msg);
// Employee: Joe Exotic, Dept: Zoo
We can also do this:
const employee: Employee = { name: "Carole Baskin", dept: "Big Cat Rescue" };
const msg = formatEmployeeMessage(employee, true, new Date());
console.log(msg);
// Employee: Carole Baskin, New: Yes, Onboarded: 2023-10-01T00:00:00.000Z
But this will throw an error:
const employee: Employee = { name: "Dillon Passage", dept: "Zoo" };
// Error: No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.
const msg = formatEmployeeMessage(employee, true);
Preferences can be configured in one of two ways:
doNotDisturb (boolean)outOfOffice (boolean)doNotDisturb (boolean)outOfOffice (boolean | string)useSystemTheme (boolean)theme (string)