如何在 TypeScript 中使用 Mobx createObservableArray?

How to use Mobx createObservableArray with TypeScript?

尝试 #1:

import { observable } from "mobx";
import { createObservableArray, IObservableArray } from "mobx/lib/internal";
export class Example1 {
    @observable items : IObservableArray<string>;

    constructor() {
        this.items = [];
    }
}

结果:

Type 'never[]' is missing the following properties from type 'IObservableArray': spliceWithArray, observe, intercept, clear, and 4 more.ts(2740)

尝试 #2:

import { observable } from "mobx";
import { createObservableArray, IObservableArray } from "mobx/lib/internal";
export class Example1 {
    @observable items : IObservableArray<string>;

    constructor() {
        this.visible = createObservableArray<string>([]);
    }
}

结果:

Expected 2-4 arguments, but got 1.ts(2554) observablearray.d.ts(41, 84): An argument for 'enhancer' was not provided.

为什么我需要这个?因为我想使用可观察数组的replace()方法:

 this.items.replace(newItems);

要实现这一点,items 必须具有 IOvservableArray 类型。否则我会得到这个错误:

Property 'replace' does not exist on type 'string[]'.

当然,我总是可以这样做:

(this.items as IObservableArray<string>).replace(items);

但考虑到我可能想要替换代码中多个位置的所有元素,这非常难看。它也不是类型安全的。如果我们不关心类型安全,那么它会更短而且不会更糟:

(this.items as any).replace(items);

但这也不是最漂亮的代码。 IObservableArray 被导出,所以我想应该有正确的使用方法并确保类型安全。但是怎么办?

我在声明可观察数组时经常使用这种模式:

readonly items = observable<string>([]);

这是否满足您的需求?