Home > front end >  How to define a function with "this" context in typescript
How to define a function with "this" context in typescript

Time:11-05

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

CodePudding user response:

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)
  • Related