PDHide
PDHide

Reputation: 19939

How to define a function with "this" context in typescript

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

Upvotes: 5

Views: 5642

Answers (2)

PDHide
PDHide

Reputation: 19939

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.org/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)

Upvotes: 0

Xetera
Xetera

Reputation: 1479

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)

Upvotes: 6

Related Questions