First Attempt:
import { observable } from "mobx";
import { createObservableArray, IObservableArray } from "mobx/lib/internal";
export class Example1 {
@observable items : IObservableArray<string>;
constructor() {
this.items = [];
}
}
Outcome of First Attempt:
The type 'never[]' is lacking the following attributes from type 'IObservableArray': spliceWithArray, observe, intercept, clear, and 4 more.ts(2740)
Second Attempt:
import { observable } from "mobx";
import { createObservableArray, IObservableArray } from "mobx/lib/internal";
export class Example1 {
@observable items : IObservableArray<string>;
constructor() {
this.visible = createObservableArray<string>([]);
}
}
Outcome of Second Attempt:
Expected 2-4 arguments, but received 1.ts(2554) observablearray.d.ts(41, 84): An argument for 'enhancer' was not given.
Reasoning Behind Needing This Change:
this.items.replace(newItems);
In order to utilize the replace() method of the observable array, the items
property must have the data structure IObservableArray
. Otherwise, the error 'Property 'replace' does not exist on type 'string[]' will be prompted.
Although there are workarounds like casting, such as:
(this.items as IObservableArray<string>).replace(items);
This approach is deemed inelegant and lacks type safety. Alternatively, a shorter but less secure method could involve:
(this.items as any).replace(items);
However, neither of these options present an aesthetically pleasing solution. Considering that IObservableArray
has been exported, it raises the question of the correct way to harness its usage while maintaining type safety. How can this be achieved?