This will log two messages:
- The first number is 3 and the second number is 4
- The first number is 6 and the second number is 7
Notice how the values passed in the call, such as 3 and 4 in logNumbers(3, 4)
, are passed to the corresponding parameters firstNumber
and secondNumber
in the function logNumbers. Then it runs the code inside the function using the provided values.
Inside the function logNumbers the parameters firstNumber
and secondNumber
are essentially variables, but don't need to be declared with let
- the name alone is all that is needed when declaring function parameters.
As you might expect, TypeScript enforces that the values passed match the type required by the function parameters. If you try calling the function with strings, e.g. logNumbers("hello", "world");
, TypeScript will mark it as an error. It is also an error to pass either too few parameters (e.g. logNumbers()
) or too many (e.g. logNumbers(3, 4, 5)
). This helps make sure your code is correct, as TypeScript will only allow you to call functions with the correct parameters and types.
Optional parameters
It's common for a function to provide optional parameters using the special notation ?:
. These must be at the end of the list of parameters, so all the required parameters come first. Then when you call the function, you have the option of omitting the optional parameters. If you omit an optional parameter, it has the value undefined
inside the function.
The function below demonstrates optional parameters. The first two parameters are required, and the third is optional, because it is declared with thirdNumber?: number
rather than thirdNumber: number
. Inside the body of the function, it acts as if it has the type number | undefined
, because it could be either of those types. You can check whether it was specified using typeof
.
function logNumbers(firstNumber: number, secondNumber: number, thirdNumber?: number)
{
console.log(`The first number is ${firstNumber} and the second number is ${secondNumber}`);
if (typeof thirdNumber === "number")
console.log(`...and the third number is ${thirdNumber}`);
}
// Can pass either two or three numbers
logNumbers(3, 4);
logNumbers(6, 7, 8);