Skip to content

Instantly share code, notes, and snippets.

@aprilrd
Last active May 8, 2018 07:02
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 aprilrd/d81e7098ea06834153381d898348ec9b to your computer and use it in GitHub Desktop.
Save aprilrd/d81e7098ea06834153381d898348ec9b to your computer and use it in GitHub Desktop.
Typescript + Redux + Typescript Readonly Interfaces
import { TypedRecord, recordify } from "typed-immutable-record";
// scaffolding
interface IPostState {
post: IPost | null;
isLoading: boolean;
}
interface IPostStateRecordPart {
post: IPostRecord; // this interface is created in a similar fashion.
isLoading: boolean;
}
interface IPostStateRecord
extends TypedRecord<IPostStateRecordPart>,
IPostStateRecord {}
function recordifyPostState(plainState: IPostState): IPostStateRecord {
return recordify<IPostStateRecordPart, IPostStateRecord>({
post: plainState.post
? recordify<IPostRecordPart, IPostRecord>(plainState.post)
: null,
isLoading: plainState.isLoading,
});
}
// reducers
const INITIAL_STATE: IPostStateRecord = recordifyPostState({
post: null,
isLoading: false,
});
function postReducer(
state: IPostStateRecord = INITIAL_STATE,
action,
): IPostStateRecord {
switch (action.type) {
case "FETCHED": {
return state.withMutations(currentState =>
currentState.set("post", action.payload.post).set("isLoading", false),
);
}
case "UPDATED_TITLE": {
return state.setIn(["post", "title"], action.payload.title);
}
default: {
return state;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment