Reputation: 2266
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
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