Skip to content

Instantly share code, notes, and snippets.

@dht
Last active January 31, 2021 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dht/5f5e9ea9ebf8ee85e58c959fa0c58fc4 to your computer and use it in GitHub Desktop.
Save dht/5f5e9ea9ebf8ee85e58c959fa0c58fc4 to your computer and use it in GitHub Desktop.
types
// ============== store ==============
export enum NodeTypes {
SINGLE_NODE = 'SINGLE_NODE',
COLLECTION_NODE = 'COLLECTION_NODE',
QUEUE_NODE = 'QUEUE_NODE',
}
export type Value = number | boolean | string | null | undefined;
export type Item = { [fieldName: string]: Value } & { id: string };
// currently used:
export type SingleNode = Record<string, any>;
export type CollectionNode = Record<string, Item>;
export type QueueNode = Item[];
export type StoreNode = SingleNode | CollectionNode | QueueNode; // prettier-ignore
export type StoreStructure = Record<string, StoreNode>;
export type Action = {
type: string;
payload: Record<string, any>;
};
export type ActionCreatorId = (id: string) => Action;
export type ActionCreatorPayload<T extends {}> = (payload: T) => Action;
export type ActionCreatorIdAndPayload<T extends {}> = (id: string, payload: T) => Action; // prettier-ignore
export type ActionCreatorEmpty = () => Action;
export type SingleBag<T> = {
patch: ActionCreatorPayload<Partial<T>>;
setAll: ActionCreatorPayload<T>;
};
export type QueueBag<T> = {
setAll: ActionCreatorPayload<T[]>;
push: ActionCreatorPayload<T>;
pop: ActionCreatorEmpty;
clear: ActionCreatorEmpty;
};
export type CollectionBag<T> = {
setAll: ActionCreatorPayload<Record<string, T>>;
add: ActionCreatorPayload<Partial<T>>;
set: ActionCreatorIdAndPayload<Partial<T> & { id: string }>;
patch: ActionCreatorIdAndPayload<Partial<T>>;
delete: ActionCreatorId;
};
export type ActionBag = SingleBag<any> | QueueBag<any> | CollectionBag<any>;
type InferArrayType<T> = T extends Array<infer P> ? P : never;
type InferCollectionType<T> = T extends Record<string, infer P> ? P : never;
export type Actions<StoreStructure> = {
[K in keyof StoreStructure]: StoreStructure[K] extends QueueNode
? QueueBag<InferArrayType<StoreStructure[K]>>
: StoreStructure[K] extends CollectionNode
? CollectionBag<InferCollectionType<StoreStructure[K]>>
: SingleBag<StoreStructure[K]>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment