Search code examples
mobxmobx-state-tree

Ensuring interface compliance in MobX State tree models


I have interfaces defined for my typescript server APIs and when defining models through MobX state tree I would like to ensure that the typescript compiler enforces that the model snapshots comply with these interfaces.

So if an additional property gets added to IFoo interface, but is not added to Foo MST model, it would be desirable to have typescript complain about it at compile time.

What is the best way to enforce the above ?


I am aware that I can get a valid typescript interface from the model itself:

type IFoo = typeof Foo.Type

I don't want to use this interface for my server APIs because:

  1. It is not desirable to have things like IObservable, IComplexType etc. in API interfaces which essentially deal with snapshots (plain objects).

  2. Interfaces derived thus also have method signatures for actions which are not desirable.


I had attempted something like:

// IFoo is my server interface
const T = t.model("Foo", {...})

type IT = typeof T.Type;

type ISnapshot<T> = {[K in keyof T]?: T[K];}
export const Foo : IModelType<ISnapshot<IFoo>, IT> = T;

But this does not seem to be working as expected.


Solution

  • The correct answer to go for would be to use the .SnapshotType Unfortunatelly we can't provide that exactly due to a lack of conditional types in TypeScript.

    Up to then you need to define your interface manually :(

    Here's the issue where you can track the progress :)

    https://github.com/mobxjs/mobx-state-tree/issues/117