javascript - How to define a function with "this" context in typescript - Stack Overflow

type Animal = {name: string}function getBear(this: Animal) : Animal {this.name = "hi"return

type Animal = {
    name: string
}

function getBear(this: Animal) : Animal {
    this.name = "hi"
    return this
}

console.log(getBear().name)

Could any one help me with this , i am not able to call the getBear function

type Animal = {
    name: string
}

function getBear(this: Animal) : Animal {
    this.name = "hi"
    return this
}

console.log(getBear().name)

Could any one help me with this , i am not able to call the getBear function

Share Improve this question asked Nov 4, 2021 at 7:13 PDHidePDHide 20k2 gold badges42 silver badges56 bronze badges 1
  • 1 You explicitly define that this has to be Animal, but you call getBear on no object so it is void. – t.niese Commented Nov 4, 2021 at 7:19
Add a ment  | 

2 Answers 2

Reset to default 6

You can't do this because the this context of getBear is not bound to an Animal when you call it. Simply telling TypeScript that this is an Animal isn't enough, you also have to call your function with that context.

In this case you would need to call it like this.

type Animal = {
    name: string
}

function getBear(this: Animal) : Animal {
    this.name = "hi"
    return this
}

console.log(getBear.call({ name: "test" }).name)

You can call this 3 ways:

type Animal = {
    name: string
}

function getBear(this: Animal, a: string): Animal {
    this.name = a
    return this
}

// First one 

// function.call(objcontext,parameters) calls a function under a different object context.
// read more at : https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

console.log(getBear.call({ name: "test" }, "Username").name)

// Here we create a object 
//second
console.log(new (getBear as any)("Username").name)

//third
console.log(new (<any>getBear)("Praveen").name)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742354010a4428077.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信