In my Angular components, I have created a class that is responsible for storing the state:
export class MyStateModel {
subState1: SubStateModel1;
substate2: SubStateModel2;
}
This class has simple subclasses:
export class SubStateModel1 {
someField1: string;
}
export class SubStateModel2 {
someField2: string;
}
Within my Angular code, there is a function that modifies the state by partially patching it using NGSX's setState
and patch
functions.
function myfunction(ctx: StateContext<MyStateModel>) {
ctx.setState(
patch({
subState1: patch({
someField1: "some value",
}),
})
);
}
Everything is working fine so far.
ISSUE: TypeScript starts giving errors when I try to make inner fields nullable or undefined:
export class SubStateModel1 {
someField1: string | null;
}
OR
export class SubStateModel1 {
someField1?: string;
}
When I set a field to null, TypeScript complains:
// TYPESCRIPT NOT HAPPY!
ctx.setState(
patch({
subState1: patch({
someField1: null,
}),
})
);
The error message states:
Argument of type 'PatchOperator<{ subState1: PatchOperator<{ someField1: null; }>; }>' is not assignable to parameter of type 'MyStateModel | StateOperator<MyStateModel >'.
Type 'PatchOperator<{ subState1: PatchOperator<{ someField1: null; }>; }>' is not assignable to type 'StateOperator<MyStateModel>'.
Types of parameters 'existing' and 'existing' are incompatible.
Type 'Readonly<MyStateModel >' is not assignable to type 'Readonly<PatchValues<{ subState1: PatchOperator<{ someField1: null; }>; }>>'.
Types of property 'subState1' are incompatible.
Type 'SubStateModel1' is not assignable to type 'PatchValues<{ someField1: null; }>'.ts(2345)
It seems like NGSX's wrapping of types in PatchOperator
objects might be causing the issue, although this shouldn't be a problem.
The specific line in the error that mentions conflicting parameters is perplexing:
Types of parameters 'existing' and 'existing' are incompatible.
I suspect that the presence of a nullable field two levels deep in the object hierarchy (a patch inside a patch involving a null) could be causing confusion. However, I can't pinpoint the exact cause of the issue.
TROUBLESHOOTING
I attempted to simplify the code structure:
const obj1 = {
someField: null,
};
const obj2 = {
subState1: patch(obj1),
};
const obj3 = patch(obj2);
ctx.setState(
obj3 // THE ERROR IS HERE (same error)
);
}