Functions
Representations
1 | function func(x: number, y: number): number { ... } |
Optional/Default/Rest parameters
By default, the number of arguments given to a function has to match the number of parameters the function expects. That’s to say, parameters can’t be too few or too many, or we will get an error.
1 | // Optional param |
This
There exist many problems using this
in JavaScript. Arrow function could help, but it’s even better with TypeScript’s this
parameter.
Example:
1 | // this will be set to window instead of obj |
Furthermore, by using this kind of method, we could prevent callback error with this
. Sometimes we want a function not to using this
, to make that constrain, we could pass this: void
as parameter.
Example:
1 | class Handler { |
Overloads
JavaScript is inherently a very dynamic language. It’s very common for a single JavaScript function to return different types of objects based on the shape of the arguments passed in. Typescript allow function to overload.
1 | function func(x: string): boolean; |
Two things need to notice:
- Order matters
Underlying JavaScript keeps an overload list and finds the match one from head. So it’s customary to order overloads from most specific to least specific. - Return any is not included in the overload list
Like above example has only two overloads: string => boolean、number => string. Callingfunc
with any other parameter types would cause an error.