Typing Functions - The Basics#

Functions#

Functions are the backbone of code reusability. TypeScript makes it painless to add type annotations to functions and it empowers us to use the latest ECMAScript function capabilities, including default parameters, destructured arguments, and arrow functions.

Annotating Functions#

Typing functions consists of two parts: typing the parameters and typing the return value. In the example below, our toNumber function takes a string or number as a parameter and returns a number:

The line that defines the input types and return type is known as the function signature. We recommended you always define a function's signature even though the input and output types will often be inferred by the TypeScript compiler. The main benefits of always defining a signature are that it gives us a form of documentation--it's easy to see the function's inputs and outputs without having to see the function body--and it ensures that the body of our function handles the correct input types while returning the correct output type. If we leave it to inference alone, we might get an any return type and lose type safety.

Optional Parameters#

It's common for some (or all) of a function's parameters to be optional. To mark a parameter as optional, we use a ? character to indicate that the parameter(s) can be ommitted when the function is called. Optional parameters must come after any and all required parameters--otherwise TypeScript will emit an error.

In the example below, formatMoney accepts a numeric amount for the first parameter followed by two optional parameters: a prefix for the output and the number of decimal places to round to:

 

This page is a preview of Beginners Guide to TypeScript

No discussions yet