Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
hastyy committed Apr 2, 2021
0 parents commit dd03d33
Show file tree
Hide file tree
Showing 12 changed files with 241 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
dist/
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "concise-redux",
"version": "0.1.0",
"description": "A minimal, type-safe abstraction on top of Redux for better developer productivity",
"main": "dist/index.js",
"types": "dist",
"scripts": {
"build": "tsc -p ."
},
"keywords": [
"typescript",
"redux"
],
"author": "João Dias",
"license": "ISC",
"devDependencies": {
"typescript": "^4.2.3"
}
}
31 changes: 31 additions & 0 deletions src/action-creator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Action } from "./types/action";
import { ActionMapConstraints } from "./types/action-constraints";
import { StringKeysOf } from "./types/utils";

export function ActionCreator<ActionMap extends ActionMapConstraints<ActionMap>>() {
return function actionFactory<
ActionType extends StringKeysOf<ActionMap>,
Payload extends ActionMap[ActionType]
>(
type: ActionType,
/**
* We use the tuple syntax to check the Payload type because, by default, conditional types distribute over unions.
* With this syntax the union type becomes atomic in the sense that the condition is
* checked against the whole type instead of its parts.
* This is necessary for the cases where Payload can be a union type, e.g., if it is a nullable type.
* More info: https://stackoverflow.com/questions/51365467/issue-with-union-types-and-conditional-types
*/
...payload: [Payload] extends [void] ? [] : [Payload]
): Action<ActionType, Payload> {
/**
* The return type of actionFactory is a conditional type.
* This works great for consuming code.
* However, the compiler is not able to match the return type from the function body. This is a design limitation.
* Because of this limitation, we need a type assertion / cast.
* More info: https://github.com/microsoft/TypeScript/issues/24929
*/
return (payload.length === 0
? { type }
: { type, payload: payload[0] }) as Action<ActionType, Payload>;
}
}
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { storeComponent } from "./store-component";
export { ActionCreator } from "./action-creator";
export type { ActionUnion } from "./types/action-union";
44 changes: 44 additions & 0 deletions src/store-component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { ActionCreator } from "./action-creator";
import { UnknownAction } from "./types/action";
import { ActionMapConstraints } from "./types/action-constraints";
import { ActionUnion } from "./types/action-union";
import { UnknownCaseReducer, CaseReducers } from "./types/case-reducers";

export function storeComponent<
ActionMap extends ActionMapConstraints<ActionMap>,
State
>({
initialState,
caseReducers,
}: StoreComponentParams<ActionMap, State>) {
return {
initialState: Object.freeze(initialState),
ActionCreator: ActionCreator<ActionMap>(),
reducer: (state = initialState, action: ActionUnion<ActionMap>) => {
const caseReducer = caseReducers[action.type];
return caseReducer
? apply(caseReducer, state, action)
: state;
}
};
}

function apply<State>(
caseReducer: UnknownCaseReducer<State>,
state: State,
action: UnknownAction
): State {
return {
...state,
...(typeof caseReducer === 'function'
? action.payload === undefined
? caseReducer(state)
: caseReducer(action.payload, state)
: caseReducer)
}
}

interface StoreComponentParams<ActionMap extends ActionMapConstraints<ActionMap>, State> {
initialState: State,
caseReducers: CaseReducers<ActionMap, State>
}
3 changes: 3 additions & 0 deletions src/types/action-constraints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { IndexableObject } from "./utils";

export type ActionMapConstraints<ActionMap> = IndexableObject & Required<ActionMap>;
7 changes: 7 additions & 0 deletions src/types/action-union.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Action } from "./action";
import { ActionMapConstraints } from "./action-constraints";
import { StringKeysOf } from "./utils";

export type ActionUnion<ActionMap extends ActionMapConstraints<ActionMap>> = {
[ActionType in StringKeysOf<ActionMap>]: Action<ActionType, ActionMap[ActionType]>;
}[StringKeysOf<ActionMap>];
15 changes: 15 additions & 0 deletions src/types/action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* We use the tuple syntax to check the Payload type because, by default, conditional types distribute over unions.
* With this syntax the union type becomes atomic in the sense that the condition is
* checked against the whole type instead of its parts.
* This is necessary for the cases where Payload can be a union type, e.g., if it is a nullable type.
* More info: https://stackoverflow.com/questions/51365467/issue-with-union-types-and-conditional-types
*/
export type Action<Type extends string, Payload> = Readonly<[Payload] extends [void]
? { type: Type }
: { type: Type, payload: Payload }>;

export interface UnknownAction {
type: string
payload?: unknown
}
18 changes: 18 additions & 0 deletions src/types/case-reducers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ActionMapConstraints } from "./action-constraints";
import { Immutable, StringKeysOf } from "./utils";

export type CaseReducers<ActionMap extends ActionMapConstraints<ActionMap>, State> = {
[ActionType in StringKeysOf<ActionMap>]: [ActionMap[ActionType]] extends [void]
? Partial<State> | UnaryCaseReducer<State>
: BinaryCaseReducer<ActionMap[ActionType], State>;
};

interface UnaryCaseReducer<State> {
(state: Immutable<State>): Partial<State>
}

interface BinaryCaseReducer<Payload, State> {
(payload: Immutable<Payload>, state: Immutable<State>): Partial<State>
}

export type UnknownCaseReducer<State> = Partial<State> | ((...args: any[]) => Partial<State>);
18 changes: 18 additions & 0 deletions src/types/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export type IndexableObject = Record<keyof never, any>;

export type StringKeysOf<T> = string & keyof T;

export type Primitive =
| null
| undefined
| string
| number
| boolean
| symbol
| bigint;

export type Immutable<T extends IndexableObject> = {
readonly [K in keyof T]: T[K] extends Primitive
? T[K]
: Immutable<T[K]>
}
67 changes: 67 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"src"
]
}

0 comments on commit dd03d33

Please sign in to comment.