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

cast stops working when types.map is used

Open safareli opened this issue 5 years ago • 3 comments

Bug report

import {
  types,
  Instance,
  cast
} from "mobx-state-tree";

export interface IItem extends Instance<typeof model> {}

export const model = types
  .model("Item", {
    content: types.string,

    // Comment this `map` out and the error on cast disappears.
    meta: types.map(types.string),
  })
  .actions((self) => {
    return {
      x: (): boolean => {
        return bla(cast(self));
      }
    };
  });

const bla = (item: IItem): boolean => {
  return true;
};

Sandbox link or minimal reproduction code https://codesandbox.io/s/mobx-cast-not-working-map-v24o6?file=/src/index.ts

Describe the expected behavior it's expected for cast to work just fine

Describe the observed behavior

but I'm getting type error when using cast and my type has map in it.

Argument of type 'string | number | boolean | null | undefined' is not assignable to parameter of type 'IItem'.
  Type 'undefined' is not assignable to type 'IItem'.ts(2345)

safareli avatar Sep 27 '20 16:09 safareli

The reason you're seeing this error is unrelated to cast and map. It's because self is typed as the model, not as model with actions, i.e., there's no x in self. IItem however requires that x is present.

A simple fix for your example would be to cast self to IItem.

 x: (): boolean => {
     return bla(self as IItem);
 }

philllies avatar Dec 12 '20 23:12 philllies

But why is that if meta is not set it works? it's not like meta is the only field, there is also content

safareli avatar Dec 14 '20 10:12 safareli

While in your example it's true that cast compiles for other types but not for types.map I don't think it's meant to be used that way. According to the docs, it "casts a node snapshot or instance type to an instance type so it can be assigned to a type instance". In your example, there's no assignment, but you're using it to match the signature another function.

philllies avatar Dec 14 '20 18:12 philllies

Hey @safareli - I know it's been a long time since this issue had any activity, but I just wanted to check in to see if @philllies answer helped you out.

If not, and this is still a problem for you, let me know and we can keep working through.

But if it was helpful, let me know and I'll close this out.

If I don't hear from you in about two weeks, I'll close this out anyway.

coolsoftwaretyler avatar Jun 28 '23 04:06 coolsoftwaretyler

It's been about two weeks with no response, so I'm gonna close this out.

coolsoftwaretyler avatar Jul 13 '23 22:07 coolsoftwaretyler