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 type for Schema #92

Open
RusovVladimir opened this issue Nov 20, 2020 · 0 comments
Open

TypeScript type for Schema #92

RusovVladimir opened this issue Nov 20, 2020 · 0 comments

Comments

@RusovVladimir
Copy link

This typings works! My be it will be useful.

I can add this typings:

// mob-x-persist-schema.ts
import { OmitProperties } from 'ts-essentials';

type SchemaFor<T> = T extends Array<infer A>
  ?
      | {
          type: 'list';
          schema: MobXPersistSchema<A>;
        }
      | false
  : T extends Map<any, infer A>
  ?
      | {
          type: 'map';
          schema: MobXPersistSchema<A>;
        }
      | false
  : T extends number | string | boolean
  ? boolean
  : T extends {}
  ?
      | {
          type: 'object';
          schema: MobXPersistSchema<T>;
        }
      | false
  : false;

type S<Q> = {
  [P in keyof Q]?: SchemaFor<Q[P]>;
};

type MobXPersistSchema<T> = S<OmitProperties<T, (...args: any[]) => any>>;

export default MobXPersistSchema;

Then I can write type-safe schema:

import { persist } from "mobx-persist";

interface PageInfo { pageNumber: number, pageSize: number }

class ListStore {
  constructor(public pageInfo: PageInfo) {
  }
}

class Store {
  constructor(public users: ListStore) {
  }
}

export const UserListStoreSchema: MobXPersistSchema<Store> = {
  users: {
    type: 'object',
    schema: {
      pageInfo: {
        type: 'object',
        schema: {
          pageNumber: true,
          pageSize: true,
        },
      },
    },
  },
};

persist(UserListStoreSchema)(Store)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant