[英]Is there any way in typescript to define optional field with type?
[英]In typescript, is there any way to define global window's extended type via typeof data?
在 typescript 中,有沒有辦法通過 typeof 數據定義全局對象的擴展類型?
例如1:
window.id = 1
interface window{
id: typeof window.id;
}
例如2:
Array.prototype.unique = function() {
return [...new Set(this)];
};
interface Array<T> {
// unique(): Array<T>;
unique(): typeof Array.prototype.unique
}
如果你想用額外的自定義屬性擴展Window
類型,你可以這樣做
const id = 1
declare global {
interface Window {
id: typeof id
}
}
window.id = 1 // OK
請注意,您的示例不會編譯,因為id
在其類型注釋中直接引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.