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:

4.1 Omitting Return Types

4.2 Mishandling Types in Functions

4.2.1 Unspecifying Callback Function Types

4.2.2 Inconsistent Parameter Types

4.2.3 Lacking Clarity with Callbacks

4.3 Misusing Optional Function Parameters

4.4 Inadequate Use of Rest Parameters

4.4.1 Using Rest Parameters with Optional Parameters

4.4.2 Using Correct Types

4.4.3 Unnecessarily Complicating the Function Signature

4.4.4 Overusing Rest Parameters

4.5 Not Understanding this

4.5.1 Misleveraging ThisParameterType for better types safety of the this context

4.5.2 Not removing this with OmitThisParameter

4.6 Being unaware of call, bind, apply and strictBindCallApply

4.7 Not Knowing About globalThis

4.8 Disregarding Function Signatures in Object Type

4.9 Incorrect Function Overloads

4.9.1 Using mismatched overload signatures

4.9.2 Having similar overloads

4.9.3 Applying excessive overloads

4.10 Misapplying Function Types

4.10.1 Overloading using function types

4.10.2 Creating overly complicated function types

4.10.3 Confusing function types with function signatures

4.10.4 Using overly generic function types

4.11 Ignoring Utility Types for Functions

4.11.1 Forgetting about typeof

sitemap