4 Functions and Methods
This chapter covers
- Enhancing type safety with overloaded function signatures done properly
- Specifying return types of functions
- Using rest parameters (…) in functions correctly
- Grasping the essence of this and globalThis in functions with the support of bind, apply, call and StrictBindCallApply
- Handling function types safely
- Employing utility types ReturnType, Parameters, Partial, ThisParameterType and OmitThisParameter for functions
Alright, brace yourself for a deep dive into the functional world of TypeScript and JavaScript. Why are we focusing on functions, you ask? Well, without functions, JavaScript and TypeScript would be as useless as a chocolate teapot. So, let's get down to business—or should I say "fun"ction? Eh, no? I promise the jokes will get better!
Now, just like an Avengers movie without a post-credit scene, JavaScript and TypeScript without functions would leave us in quite a despair. TypeScript, being the older, more sophisticated sibling, brings to the table a variety of function flavors that make coding more than just a mundane chore.
First off, we have the humble function declaration, the JavaScript original that TypeScript inherited:
function greet(name) { console.log(`Hello, ${name}!`); } greet('Tony Stark'); // Logs: "Hello, Tony Stark!"
Then TypeScript, in its pursuit of stricter typing, added types to parameters and return values: