如何在打字稿中使用 "this" 上下文定义函数

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)

谁能帮我解决这个问题,我无法调用 getBear 函数

您不能这样做,因为当您调用它时,getBearthis 上下文未绑定到 Animal。简单地告诉 TypeScript this 是一个 Animal 是不够的,您还必须使用该上下文调用您的函数。

在这种情况下,您需要这样调用它。

type Animal = {
    name: string
}

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

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

您可以通过 3 种方式调用它:

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)