The Utils Folder 10 exercises
Problem

Adapt a Function to Handle Different Types of Arguments

Consider this sum function, which can accept different types of arguments:


function sum(valuesOrA: { a: number; b: number } | number, b?: number): number {
if (typeof valuesOrA === "object") {
return valuesOrA.a + valuesOrA.b;
}
return valuesOrA + b!;
}

The sum function t

Loading exercise

Transcript

00:00 We're now gonna look at function overloads in TypeScript. We have a sum function here, and this sum function takes in a couple of different parameters here. The two parameters it takes are values or A, which can either be an object with A number and B number or number, or it can take in B number here,

00:19 and this is an optional parameter. Then inside it checks if values or A is an object, and if it does, if it is an object, then it returns values or A, or values or A plus B, or it returned values or A plus B here. So this is pretty hard to read, but essentially what this is doing is we have a sum function

00:38 which we can either pass in an object or we can pass in two numbers there. Now, this is interesting because actually as it's currently declared, this function lets us pass in various kind of invalid combinations, so we should be getting a warning here when we try to pass in an object

00:56 and a second parameter. We should also be getting a warning when we don't pass in enough arguments. The sum function basically lets us call it in ways which are actually invalid and don't really work. Your job is to try to work out how using function overloads we can declare this function in a slightly different way

01:15 to make sure that it can only be called in certain patterns. Good luck.