For a demonstration, you can check out the implementation in this codesanbox. The class "Operation.ts" contains all the details.
The purpose of the "Operation" class is to manage operations performed on objects such as rectangles. Each operation type ("move", "rotate", etc.) has its own specific operation data structure (move: [number, number], rotate: number, etc.). To accommodate these various types, I used generics within the class definition. The _type property represents the type T and the _operation property refers to OperationMap[T] to correctly identify the operation for each operation type.
After executing an operation using the Operation class, I aim to store both the original operationData and its reverse counterpart for future reference. However, I encountered two errors which I am unable to comprehend fully. Despite checking the _type variable to determine the type T, Typescript seems to struggle with recognizing the operationData and reversedOperationData types.
It appears there might be a gap in my understanding of how Typescript handles types in this context. I have scoured resources but haven't found a satisfactory explanation yet. Any assistance or insights would be greatly appreciated.
type operationTypes = "move" | "rotate" | "rename";
type operationsMap = {
move: [number, number];
rotate: number;
rename: string;
};
type operationsDataMap = {
move: [number, number];
rotate: number;
rename: [string, string]; // before, after
};
export class Operation<T extends operationTypes> {
_type: T;
_operation: operationsMap[T];
_operationData: operationsDataMap[T] | null = null;
_ReversedOperationData: operationsDataMap[T] | null = null;
constructor(type: T, operation: operationsMap[T]) {
this._type = type;
this._operation = operation;
}
set operationData(operationData: operationsDataMap[T]) {
this._operationData = operationData;
if (this._type === "move") {
this._ReversedOperationData = [-operationData[0], -operationData[1]]; // Issue lies here
}
if (this._type === "rotate") {
// Handle reverse rotation
}
if (this._type === "move") {
// Handle reverse renaming
}
}
}