Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
andreykurilin opened this issue Oct 11, 2024 · 1 comment
Assignees
Labels
Typescript Issue related to Typescript typings

Comments

@andreykurilin
Copy link

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; }>; }'.

@thegedge thegedge added the Typescript Issue related to Typescript typings label Oct 11, 2024
@thegedge thegedge self-assigned this Oct 11, 2024
@coolsoftwaretyler
Copy link
Collaborator

Thanks for the issue report @andreykurilin, and I'm sorry for the inconvenience!

I see @thegedge has assigned this to himself, so I expect good things here.

I put together a CodeSandbox with the repro code in case that helps demonstrate the issue for others: https://codesandbox.io/p/sandbox/g3w8ft?file=%2Fsrc%2Findex.ts%3A8%2C15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Typescript Issue related to Typescript typings
Projects
None yet
Development

No branches or pull requests

3 participants