Sijan Shrestha
Sijan Shrestha

Reputation: 2266

How to correctly apply type for this during .call() method?

I am having trouble trying to figure out a solution for the following

interface IName {
  name:string;
}

let obj1:IName = {
  name: "LINUS"  
}


function profileInfo (age:number,location:string):string{
  return `${this.name} is ${age} years old and is from ${location}` // << Error here  as 'this' implicitly has type 'any' because it does not have a type annotation
}

// call
let res = profileInfo.call(obj1,23,'Bangkok')
console.log(res);

I was experimenting with the call method which actually will bind the obj1 with the profileInfo function.

Any suggestion or solution is much appreciated.

The code does work on normal js though.

Upvotes: 0

Views: 77

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52133

Use a this parameter annotation:

function profileInfo(this: IName, age: number, location: string): string {
    return `${this.name} is ${age} years old and is from ${location}`
}

Note this will expose errors where you call profileInfo without the expected this context:

// Bad call:
profileInfo(23, 'Amsterdam'); // Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'IName'.

Upvotes: 3

Related Questions