How to describe model of mobx-state-tree with interface of typescript with optional fields?

22 views Asked by At

I have monorepo consists of 3 packages FE (ReactJS), BE (NestJS) and shared-types (types/interfaces shared between FE and BE).

In share-types I have User interface

interface User {
  firstName?: string;
  lastName?: string;
  email: sting;
}

In FE I have created the model:

export const UserModel = types.model('User', {
  firstName: types.maybe(types.string),
  lastName: types.maybe(types.string),
  email: types.string,
});

This UserModel used in AuthModel

export const AuthModell = types
  .model('Auth', {
    isAuthenticated: false,
    user: UserModel
  })
  .actions(self => ({
    login: flow(function* (authData: AuthData): Generator<Promise<User | null>, User | undefined, AxiosResponse<User>>  {
      const res = yield axios.post('/auth/login', authData);

      if (res.status === 201) {
        const user = res.data;

        if (user) {
          self.isAuthenticated = true;
          self.user = user;

          return user;
        }
      }

      return undefined;
    }),
    setUser(user: User | undefined) {
      self.user = user;
    }
  }));

This solution raise the TS error Type 'User' is not assignable to type ... because User interface have optional fields firstName and lastName.

When I check the type that generate MST I have found that in MST type firstName, lastName are not optional:

type TUser = Instance<typeof UserModel>;

type TUser = {
  firstName: string;
  lastName: string;
  email: string;
} & NonEmptyObject & IStateTreeNode<...>

So the question is: how to create UserModel compatible with User interface which shared between all packages in monorepo?

0

There are 0 answers