Is it possible to implement this functionality using TypeScript?
There exist objects that define various "actions".
export interface IAction {
action: string;
data: any;
otherParam1: number;
otherParam2: number;
}
The 'action' property is a string with a predefined set of values ("one", "two", "three" for example). Each action has different data format associated with it.
export interface IActionOneData {
x: number;
}
export interface IActionTwoData {
y: number;
z: string;
}
export interface IActionThreeData {
someList: Array<string>;
}
The intention is to handle actions based on their specific data formats (e.g. if action is "one", then use "one-format").
function doAction(action: IAction): void {
if (action.action === "one") {
console.log("x = " + action.data.x);
}
// ...
}
My initial approach (which isn't functioning as expected):
export enum ActionTypes {
one = "one",
two = "two",
}
export interface IAction {
action: ActionTypes;
data: any;
otherParam1: number;
otherParam2: number;
}
export interface IActionOneData {
x: number;
}
export interface IActionOne extends IAction {
action: ActionTypes.one;
data: IActionOneData;
}
function doAction(action: IAction): void {
if (action.action === ActionTypes.one) {
console.log("x = " + action.data.undef); // no error, data is any
}
// ...
}