Typescript - Tips & Tricks - this parameter

Hello everybody and welcome back, today I'll talk about this parameter. Sometimes we need to create...

#typescript #webdev
Luca Del Puppo Luca Del Puppo
Article Series · Part 6 of 21 TypeScript - Tips & Tricks
View full series (21)
  1. #5 Previous
    Overloaded Functions
  2. #6 Reading now
    this parameter
  3. #7 Up next
    any vs. unknown
Browse all 21 parts in this series
  1. #1 typeof
  2. #2 Literal Types
  3. #3 keyof
  4. #4 Union and Intersection
  5. #5 Overloaded Functions
  6. #6 this parameter Current
  7. #7 any vs. unknown
  8. #8 Optional modifier
  9. #9 Index Signature
  10. #10 readonly modifier
  11. #11 Readonly Array
  12. #12 Tuple
  13. #13 Non-null assertion operator
  14. #14 Never type
  15. #15 Assert Function
  16. #16 Type Guard
  17. #17 Conditional Type
  18. #18 infer keyword
  19. #19 Mapped Types
  20. #20 Advanced Types
  21. #21 Rest Parameters & Rest Arguments

Hello everybody and welcome back, today I’ll talk about this parameter.

Sometimes we need to create functions that have to know the context to run correctly. A simple example, the mathematical power must know the base and the exponent number to run correctly. So we could create a simple method like this:

function pow(exponent: number) {
  return Math.pow(this.number, exponent);
}

const basePow = {
  base: 2,
  pow,
};

console.log(basePow.pow(2));

If we build and run this code, the console log’s result will be “NaN”, because in the pow method the value of the field “this.number” is undefined. N.B. if you build this code with the strict mode on true, the compiler detects the problem at build time and so the build fails

But now I explain the solution. In this case, the problem is the “number” field that doesn’t exist in this context. Typescript helps us to prevent this error, it allows us to indicate the “this” type as a parameter. To do this, we need to declare the “this” context as the first parameter of the function, so typescript detects the “this” type and it helps us to prevent errors and bugs. So the code in the previous example should be rewritten like this:

function pow(this: { base: number }, exponent: number) {
  return Math.pow(this.base, exponent);
}

const basePow = {
  base: 2,
  pow,
};

console.log(basePow.pow(2));

In this case, the result at runtime is “4” as expected. If by chance we write the “basePow” object like this:

const basePow = {
  value: 2,
  pow,
};

when we try to call the method “basePow.pow(2)”, the typescript language detects the error, and in this case, when we try to build the code the build fails.

That’s all! See you soon guys!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.