Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add mobx typescript support?

enter image description here

As what you can see, the "replace" method is not support by ts. Maybe I should use IObservableArray instead of Array, but another problem occurred.

enter image description here

like image 774
ParallelZebra Avatar asked Jul 01 '26 00:07

ParallelZebra


1 Answers

There are a few solutions. but yes you should use IObservableArray so you make sure you have and use the right methods.

I used this work around:

 this.files = [] as any;

or a more cast type once solution:

 function MyArray<T>(): IObservableArray<T> {
     return [] as any; // disable eslint once here.
 }

 this.files = MyArray();

Advised solution

This issue was discussed before on github: https://github.com/mobxjs/mobx/issues/669

The solution provided is to set it as readonly property once:

class AppModel {
  readonly files = observable<IFile>([])
}

this is the shortest typed solution that also makes sure you wont set this.files again mistakenly (and losing all your observers).

like image 166
Joel Harkes Avatar answered Jul 05 '26 07:07

Joel Harkes