TypeScript
Templating is available for projects using TypeScript. For example, if you create an action that will take a string as a parameter, it would look like the below example.
class ThemeStateController extends StateController<ThemeState> {
// ...
public readonly setTheme = this.createReducingAction<string>(
(state: ThemeState, theme: string) => ({
...state,
theme,
})
);
}
ThemeStateController.getInstance(objectiveStore).setTheme(); // error
ThemeStateController.getInstance(objectiveStore).setTheme(10); // error
ThemeStateController.getInstance(objectiveStore).setTheme({}); // error
ThemeStateController.getInstance(objectiveStore).setTheme('dark'); // works
You can also set the action template type to <void> to indicate that no parameter should be taken by the action.
The template variable for actions is optional. For example, the following will also work:
class ThemeStateController extends StateController<ThemeState> {
// ...
// The template variable will be inferred from the payload parameter type (string, in this example)
public readonly setTheme = this.createReducingAction(
(state: ThemeState, theme: string) => ({
...state,
theme,
})
);
}
In the above example, TypeScript will correctly infer that the action takes a string payload.
This also works for StatelessController classes, as shown below:
class MyStatelessController extends StatelessController {
public foo = this.createSagaAction(
function* (action: { type: string; payload?: string }) {
//
}
).register();
public bar = this.createSagaAction(
function* () {
//
}
).register();
}
MyStatelessController.getInstance(objectiveStore).foo('okay'); // works
MyStatelessController.getInstance(objectiveStore).foo(123); // error
MyStatelessController.getInstance(objectiveStore).foo(); // error
MyStatelessController.getInstance(objectiveStore).bar(); // works
MyStatelessController.getInstance(objectiveStore).bar('okay'); // error
MyStatelessController.getInstance(objectiveStore).bar(123); // error