我正在為 vanilla JS 庫撰寫 TypeScript 宣告檔案。main 函式接受一個可以包含函式的 config 引數,如下所示:
interface Config {
id: string
onOpen?: () => void
}
所有來自的屬性config都被添加到另一個型別的物件主函式中Foo:
interface Foo {
someKey: number,
onOpen: () => void // Set to the onOpen function passed to mainFunction
}
function mainFunction(config: Config): Foo
由于函式 fromconfig僅在Foo物件的背景關系中呼叫,因此this關鍵字應在 的范圍內Foo。這意味著以下內容已傳遞給mainFunction...
mainFunction({
id: 'abc',
onOpen: function () {
alert(this.someKey)
}
})
...this.someKey將從Foo物件中檢索。
有沒有辦法說介面上的任何函式Config都有thistype 關鍵字Foo?
uj5u.com熱心網友回復:
您可以為回呼型別指定一個this引數:
interface Config {
id: string
onOpen?: (this: Foo) => void
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352362.html
標籤:打字稿
