mobx-state-tree icon indicating copy to clipboard operation
mobx-state-tree copied to clipboard

TypeScript does not recognize overriding mandatory property with optional one in sub-model

Open andreykurilin opened this issue 4 months ago • 1 comments

Minimal reproduction code


import { types } from 'mobx-state-tree';

export const ErrorStore = types
  .model('ErrorStore', {
    value: '',
  })
  .actions((self) => ({
    set(value: string) {
      self.value = value;
    },
    reset() {
      self.value = '';
    },
  }))
  .views((self) => ({
    get formattedValue() {
      return self.value;
    },
  }));

export const NoDisplayError = ErrorStore.named('NoDisplayError').views(() => ({
  get formattedValue() {
    return undefined;
  },
}));


const InputStore = types.model("InputStore", {
    value: "",
    // developer should explicitly specify whether validation errors should be displayed or not
    error: types.union(ErrorStore, NoDisplayError)
});


const PasswordInputStore = InputStore.named("PasswordInputStore").props({
    // we have strict requirements for password, so validation errors should be displayed by default
    error: types.optional(types.union(ErrorStore, NoDisplayError), () => ErrorStore.create({}))
});


const passwordS = PasswordInputStore.create({});

Describe the expected behavior

Initialization of PasswordInputStore should not require specifying optional error property.

Describe the observed behavior

TypeScript fails as error property is not provided.

      TS2345: Argument of type '{}' is not assignable to parameter of type 'ModelCreationType<{ value: string | undefined; error: EmptyObject & Partial<{ value: string | undefined; }>; }>'.
  Property 'error' is missing in type '{}' but required in type '{ error: EmptyObject & Partial<{ value: string | undefined; }>; }'.

andreykurilin avatar Oct 11 '24 09:10 andreykurilin