Typing
Typing is used to type the method arguments.
Why do we need typing?
Let's say, we are adding a function in the store dynamically using the addFunction method. Then, the store should have an additional typing of executeFunction with those arguments. We end up overloading the typing of executeFunction by exporting the method type to the store.
Example
- We are adding two functions in the store and exporting their type.
ClickMePlugin.tsx
class ClickMePlugin implements IPlugin {
namespace = "ClickMe";
activate(): void {
this.pluginStore.addFunction(
`${this.namespace}.sendAlert`,
(msg: string) => {
alert(msg);
}
);
this.pluginStore.addFunction(
`${this.namespace}.add`,
(a: number, b: number) => {
console.log(a + b);
}
);
}
//rest of the code
}
export default ClickMePlugin;
type PluginStoreClickMe = {
executeFunction(functionName: `ClickMe.sendAlert`, msg: string): void;
executeFunction(functionName: `ClickMe.add`, a: number, b: number): void;
};
export type { PluginStoreClickMe };
- When building a complex app, we have many types of exporting from each Plugin. So, it is difficult to import all the types repeatedly wherever we want to use pluginStore. Instead, let us create a type by combining all the plugins and use it as a single type as shown in types.tsx.
types.ts
import { PluginStore } from "react-pluggable";
import { PluginStoreClickMe } from "./plugins/ClickMePlugin";
export type PluginStoreWithPlugins = PluginStore & PluginStoreClickMe;
- Now when we declare the type of PluginStore as PluginStoreWithPlugins while creating (see App.tsx) or retrieving(see Test.tsx) pluginStore, it will import all the types contained in PluginStoreWithPlugins to pluginStore.
App.tsx
import { PluginStoreWithPlugins } from "./types";
const pluginStore: PluginStoreWithPlugins = createPluginStore();
Test.tsx
const Test = (props: any) => {
const pluginStore: PluginStoreWithPlugins = usePluginStore();
//code
};
So whenever you write pluginStore.executeFunction(), it will give you a hint to put arguments inside it as shown below.