mobx-persist icon indicating copy to clipboard operation
mobx-persist copied to clipboard

TypeScript type for Schema

Open RusovVladimir opened this issue 4 years ago • 0 comments

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)

RusovVladimir avatar Nov 20 '20 15:11 RusovVladimir