Functions
Learn about TypeScript function type safety, optional parameters, default parameters, and rest parameters,
We'll cover the following...
Exploring the type system with functions
TypeScript language can be used to introduce further type safety whenever functions are used. Functions can use optional parameters and spread syntax. We will look at how we can define a function signature in such a manner that if a function defines another function as a parameter, we can make sure that the function we pass in has the correct parameters.
Optional parameters
Similar to tuples in TypeScript, we can specify that a function can have optional elements in the same way, using the question mark (?
).
Consider the following code:
// This function concatenates two string values, "a" and "b", and logs the result to the console.// The second parameter "b" is optional, indicated by the "?" after its type declaration.function concatValues(a: string, b?: string) {console.log(`a + b = ${a + b}`);}// Call the function with two argumentsconcatValues("first", "second");// Call the function with only one argumentconcatValues("third");
-
We define a function named
concatValues
from lines 3–5 that has two parameters,a
andb
, both of type string. The second argument,b
, however, has been marked as optional using the question mark (?
) after the argument name, that is,b?: string
. -
We then call this function with two parameters on line 8 and then with only a single parameter on line 11.
We can see from the output that the first call to the concatValues
function concatenates the strings ...