mirror of
https://github.com/muerwre/muerwre.github.io.git
synced 2025-04-25 02:46:39 +07:00
1.5 KiB
1.5 KiB
Sometimes you want to add global variable to your window
. That thing's called global module augmentation.
Say you need to call window.doFancyThings()
. For that you should augment global window
interface in *.d.ts
file:
declare global {
interface Window {
doFancyThings: () => void;
}
}
This is useful for declaring global window.ethereum
(or window.web3
) in blockchain projects with typescript, which use wallet browser extensions.
Augmenting existing interface
For example, you have class Sample
without any functionality:
// Sample.ts
export class Sample {
// nothing :-)
}
Then you want extend it with doFancyThings()
method. That can be achieved with said module augmentation:
// fancyThings.ts
import { Sample } from "./Sample";
declare module "./Sample" {
interface Sample {
doFancyThings: () => void;
}
}
Now you can call sample.doFancyThings()
by importing both .ts
files:
import { Sample } from "./sample";
import "./fancyThings";
const sample = new Sample();
sample.doFancyThings(); // ok
This example is useful for adding global properties to component in vue.js.