One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner:
interface StateTree {
readonly subState1: SubState1;
readonly subState2: SubState2;
}
interface SubState1 {
readonly a: number;
readonly b: string;
}
interface SubState2 {
readonly c: {
readonly d: symbol;
readonly e: string;
};
}
This approach eliminates the need for libraries like ImmutableJS and provides strong guarantees when accessing the read-only state tree, as shown here:
const state: StateTree = getState();
state.subState2.c.e
However, the question arises: Is there a method to maintain immutability and type-safety while creating modified copies of these read-only state trees?
I initially considered using Object.assign()
, which ensures immutability but lacks compile-time type-safety due to TypeScript's behavior with type intersection (refer to this discussion).