Search code examples
javascripttypescriptmobxmobx-react

Mobx - Object literal may only specify known properties


I recently started to learn how to use Mobx to manage my application's state and recently I came across the following error:

Object literal may only specify known properties, and "data" does not exist in type "AnnotatiosMap<this, never>".

This happens whenever I want to make a property of my class private. However, if it is public or protected, the problem does not occur.

This is a small snippet of my code:

import { makeObservable, observable } from "mobx";

class Base {
  private data: string[];

  constructor() {
    this.data = [];

    makeObservable(this, {
      data: observable,
    });
  }

  public getData = (): string[] => {
    return this.data;
  };

}

export default new Base();

What should I do to make my property private but still being watched?

Have a great day!


Solution

  • From the docs:

    By default TypeScript will not allow you to annotate private fields. This can be overcome by explicitly passing the relevant private fields as generic argument, like this: makeObservable<MyStore, "privateField" | "privateField2">(this, { privateField: observable, privateField2: observable })