[英]Type annotation for `this` keyword in Typescript
我有一個獨立的函數,它意味着使用Function.prototype.call
提供的上下文。
例如:
function foo () {
return this.bar;
}
> foo.call({bar: "baz"})
baz
有沒有辦法在此場景中為this
關鍵字提供Typescript類型注釋?
在我看來,它有點難看。
首先,你可以使用特殊this
參數的語法來識別你所期望的對象類型this
是:
function foo (this: {bar: string}) {
return this.bar; // no more error
}
如果直接調用它會有幫助:
foo(); // error, this is undefined, not {bar: string}
var barHaver = { bar: "hello", doFoo: foo };
barHaver.doFoo(); // acceptable, since barHaver.bar is a string
var carHaver = { car: "hello", doFoo: foo };
carHaver.doFoo(); // unacceptable, carHaver.bar is undefined
但是你想使用foo.call()
。 不幸的是,在TypeScript中鍵入的Function.prototype.call()
不會真正為您強制執行此限制:
foo.call({ bar: "baz" }); // okay, but
foo.call({ baz: "quux" }); // no error, too bad!
將更好的東西合並到TypeScript的Function
聲明中會給我帶來問題,(丑陋的第一點;你需要將foo
為某些東西)所以你可以嘗試這樣的東西:
interface ThisFunction<T extends {} = {}, R extends any = any, A extends any = any> {
(this: T, ...args: A[]): R;
call(thisArg: T, ...args: A[]): R;
}
甲ThisFunction<T,R,A>
是具有一個功能this
類型的T
,類型的返回值R
和類型的其余參數A[]
(第二點丑陋:你不能以類型系統強制執行的方式輕松指定不同類型的多個參數。)
然后你可以將foo
為ThisFunction<{ bar: string }, string>
,(第三點丑陋:類型系統不會推斷出this
類型)然后最后使用call()
:
(<ThisFunction<{ bar: string }, string>>foo).call({ bar: "baz" }); // okay, and
(<ThisFunction<{ bar: string }, string>>foo).call({ baz: "quux" }); // error, hooray!
希望有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.