Functions | Typescript
Inferring the types#
TypeScript compiler can figure out the type even if you only have types on one side of the equation:
This is called "contextual typing", a form of type inference.
Optional and Default Parameters#
Optional parameters and trailing default parameters will share commonality in their types, so both
and
share the same type (firstName: string, lastName?: string) => string.
default-initialized parameters don't need to occur after required parameters
Rest Parameters#
this#
Understanding JavaScript Function Invocation and "this".
this parameters#
this parameters are fake parameters that come first in the parameter list of a function:
Let's add a couple of interfaces to our example above, Card and Deck, to make the types clearer and easier to reuse:
Now TypeScript knows that createCardPicker expects to be called on a Deck object.
That means that this is of type Deck now, not any, so --noImplicitThis will not cause any errors.
Overloads#
In order for the compiler to pick the correct type check, it follows a similar process to the underlying JavaScript. It looks at the overload list and, proceeding with the first overload, attempts to call the function with the provided parameters. If it finds a match, it picks this overload as the correct overload. For this reason, it's customary to order overloads from most specific to least specific.
Note that the function pickCard(x): any piece is not part of the overload list, so it only has two overloads: one that takes an object and one that takes a number.
Calling pickCard with any other parameter types would cause an error.