Skip to content

Instantly share code, notes, and snippets.

@jfet97
Created March 21, 2020 14:55
Show Gist options
  • Save jfet97/0d371f82e115168733feebb04498f3b0 to your computer and use it in GitHub Desktop.
Save jfet97/0d371f82e115168733feebb04498f3b0 to your computer and use it in GitHub Desktop.
type ActionsTypesExample = "INIT" | "SYNC" | "LOG_IN" | "LOG_IN_SUCCESS" | "LOG_OUT"
type SafeKeyValueMapExample<KS extends keyof any> = {
readonly [K in KS]: K;
};
const ACTIONS_TYPES_MAP_EXAMPLE: SafeKeyValueMapExample<ActionsTypesExample> = {
INIT: "INIT",
SYNC: "SYNC",
LOG_IN: "LOG_IN",
LOG_IN_SUCCESS: "LOG_IN_SUCCESS",
LOG_OUT: "LOG_OUT"
}
type ActionInitExample = {
type: typeof ACTIONS_TYPES_MAP_EXAMPLE.INIT
}
type ActionSyncExample = {
type: typeof ACTIONS_TYPES_MAP_EXAMPLE.SYNC
}
type ActionLogInExample = {
type: typeof ACTIONS_TYPES_MAP_EXAMPLE.LOG_IN
emailAddress: string
}
type ActionLogInSuccessExample = {
type: typeof ACTIONS_TYPES_MAP_EXAMPLE.LOG_IN_SUCCESS
accessToken: string
}
type ActionLogOutExample = {
type: typeof ACTIONS_TYPES_MAP_EXAMPLE.LOG_OUT
}
type ExtractImplementedTypesExample<T> = T extends { type: infer U } ? U : T
type ActionsTypesTotalityCheckerExample<T, U> = [U] extends [ExtractImplementedTypesExample<T>]
? ExtractImplementedTypesExample<T> extends U
? T : never : never
type ActionExample = ActionsTypesTotalityCheckerExample<
(ActionInitExample | ActionSyncExample | ActionLogInExample | ActionLogInSuccessExample | ActionLogOutExample), ActionsTypesExample>
function dispatch(action: ActionExample): number {
switch (action.type) {
case ACTIONS_TYPES_MAP_EXAMPLE.INIT: {
action; // Action Init
// fai cose
return 1
}
case ACTIONS_TYPES_MAP_EXAMPLE.SYNC: {
action; // Action Sync
return 2
}
case ACTIONS_TYPES_MAP_EXAMPLE.LOG_IN: {
action.emailAddress; // Action Init
return 3
}
case ACTIONS_TYPES_MAP_EXAMPLE.LOG_IN_SUCCESS: {
action.accessToken; // Action LogIn Success
return 4
}
case ACTIONS_TYPES_MAP_EXAMPLE.LOG_OUT: {
action; // Action LogOut Success
return 5
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment