[英]Typescript this as a function parameter/return type
我希望能夠在函數的參數/返回類型中引用當前 object 的類型,例如以下:
在.d.ts
中:
interface Object {
add(object: Partial<this>): this;
}
在.js
中:
Object.prototype.add = function(object) {
Object.assign(this, object);
}
此 function 的預期行為是僅允許參數包含已通過Partial<this>
在 object 上定義的屬性。 但是,在嘗試使用時,例如
document.body.style.add({
fontSize: "12px"
});
TypeScript 給我以下錯誤:
Argument of type '{ fontSize: string; }' is not assignable to parameter of type `Partial<Object>`.
Object literal may only specify known properties, and 'fontSize' does not exist in type 'Partial<Object>'.
我認為這是因為我的.d.ts
中的this
類型實際上只是指Object
因為這是 function 的包含接口,而不是識別document.body.style
是的CSSStyleDeclaration
類型。 我怎樣才能實現這樣的 function ,它使用 object 的類型作為參數/返回類型? 這在 TypeScript 中是否可行?
免責聲明:以這種方式修改原生原型被認為是不好的做法。 您可能有一些理由可以為您的用例執行此操作,但您可能應該避免它。 無論如何,讓我們繼續前進。
As you noticed, the polymorphic this
type doesn't really work the way you want for the native interface
types like Object
, String
, etc.. Even known subtypes of Object
will see this
rendered as Object
instead of the known subtype.
作為一種解決方法,您可以通過使方法通用並為其提供通用的this
參數來模擬所需的行為:
interface Object {
add<T>(this: T, object: Partial<T>): T;
}
所以現在如果你在一些CSSStyleDeclaration
類型的 object 上調用add()
,類型檢查器將推斷T
是CSSStyleDeclaration
,因此期望Partial<CSSStyleDeclaration>
作為它的參數。 因此,以下工作按預期工作:
document.body.style.add({
fontSize: "12px"
});
// (method) Object.add<CSSStyleDeclaration>(
// this: CSSStyleDeclaration, object: Partial<CSSStyleDeclaration>
// ): CSSStyleDeclaration
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.