Exercise - Create functions
In this exercise, you'll create two named functions with strongly typed parameters and return values.
Open the Playground and remove any existing code.
Copy the following JavaScript function into the Playground. Notice that the parameter
message
implicitly has anany
type.function displayAlert(message) { alert('The message is ' + message); }
Now, assign the
string
type to themessage
parameter. This named function doesn't return a value so you can leave off the return type (you can also pass backvoid
as the return type, but it isn't necessary to do so.)function displayAlert(message: string) { alert('The message is ' + message); }
Try calling the function, passing in a
string
as a parameter. Now, try passing in anumber
. TypeScript type checks the parameter and notifies you of the conflict. Depending on what you're trying to accomplish with this function, you can either put the number in quotes, expand the types of values accepted by the parameter with a union type (for examplemsg: string | number
), or add some logic to your function to handle the different types of values passed into it.Here's another example. The
sum
function totals the numbers in an array and returns the result. Copy the JavaScript code into the Playground.function sum(input) { let total = 0; for(let count = 0; count < input.length; count++) { if(isNaN(input[count])){ continue; } total += Number(input[count]); } return total; }
Try calling the function with a single number as a parameter, for example,
sum(5)
. It accepts the value but doesn't return the correct result because the parameter isn't passed as an array.Set the type of the
input
parameter to an array ofnumber
values, set the return type of the function tonumber
, and set the type of thetotal
variable tonumber
.function sum(input: number[]): number { let total: number = 0; for(let count = 0; count < input.length; count++) { if(isNaN(input[count])){ continue; } total += Number(input[count]); } return total; }
Now, if you call the function with
sum(5)
, TypeScript flags the type issue with the parameter.Try calling the function with an array of values that have mixed types, for example,
sum([1, 'two', 3]
). The values inside the array are type checked, and TypeScript returns the error:Type 'string' is not assignable to type 'number'.