Search code examples
typescriptmobxtypescript2.0mobx-state-tree

Pick some properties from generated Instance of type is not working, why?


Trying to generate an new type with only some properties, but I'm getting nothing..

const User = types.model({
    id: types.identifier,
    username: types.maybe(types.string),
    email: types.maybe(types.string),
});
type TUser = Instance<typeof User>;
type TDatabaseUser = Pick<TUser, 'id' | 'email'>

TDatabaseUser has no properties.. and should have id and email

What I'm doing wrong ?

enter image description here


Solution

  • Your code seems to be working as intended.

    import { Instance, types } from "mobx-state-tree";
    
    const User = types.model({
      id: types.identifier,
      username: types.maybe(types.string),
      email: types.maybe(types.string)
    });
    type TUser = Instance<typeof User>;
    type TDatabaseUser = Pick<TUser, "id" | "email">;
    
    const dbUser: TDatabaseUser = {
      id: "1",
      email: "test@test.com",
      // id and email works, but username gives rise to an error.
      username: "does not work"
    };