如何在.call()方法期间为此正确应用类型?

时间:2019-06-18 16:43:15

标签: typescript

我在尝试解决以下问题时遇到困难

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);

我正在尝试使用call方法,该方法实际上会将obj1与profileInfo函数绑定在一起。

任何建议或解决方案都值得赞赏。

虽然该代码确实适用于普通js。

1 个答案:

答案 0 :(得分:3)

使用this parameter批注:

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

请注意,这将在没有预期的profileInfo上下文的情况下调用this时暴露错误:

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