0
0
Typescriptprogramming~20 mins

ThisParameterType and OmitThisParameter in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using ThisParameterType and OmitThisParameter in TypeScript
📖 Scenario: Imagine you are creating a simple calculator object with methods that use this to access its properties. You want to learn how to extract the type of this from these methods and how to create versions of these methods without the this parameter.
🎯 Goal: You will build a TypeScript example that shows how to use ThisParameterType to get the type of this from a method, and how to use OmitThisParameter to create a function type without the this parameter.
📋 What You'll Learn
Create an object with a method that uses this
Create a type alias using ThisParameterType to get the this type
Create a type alias using OmitThisParameter to remove the this parameter
Call the method with and without this parameter
💡 Why This Matters
🌍 Real World
Understanding how to handle the <code>this</code> parameter is important when working with object methods and callbacks in TypeScript, especially when you want to reuse methods without binding them.
💼 Career
Many TypeScript jobs require working with complex object types and functions. Knowing how to manipulate <code>this</code> types helps write safer and more flexible code.
Progress0 / 4 steps
1
Create a calculator object with a method using this
Create a constant called calculator with a method add that takes a number value and returns the sum of this.base and value. The object should have a property base set to 10.
Typescript
Need a hint?

Remember to define this type explicitly in the add method.

2
Create a type alias using ThisParameterType to get the this type of add
Create a type alias called AddThisType that uses ThisParameterType on typeof calculator.add.
Typescript
Need a hint?

Use ThisParameterType with typeof calculator.add to get the this type.

3
Create a type alias using OmitThisParameter to remove the this parameter from add
Create a type alias called AddWithoutThis that uses OmitThisParameter on typeof calculator.add.
Typescript
Need a hint?

Use OmitThisParameter with typeof calculator.add to remove the this parameter.

4
Call the add method with and without this parameter
Create a constant result1 by calling calculator.add with calculator as this and 5 as argument. Create a constant addFn of type AddWithoutThis assigned to calculator.add. Then create a constant result2 by calling addFn with 5. Finally, print result1 and result2 separated by a space.
Typescript
Need a hint?

Use call to call add with this. Assign calculator.add to a variable of type AddWithoutThis and call it without this.