Last active
May 8, 2018 07:02
-
-
Save aprilrd/d81e7098ea06834153381d898348ec9b to your computer and use it in GitHub Desktop.
Typescript + Redux + Typescript Readonly Interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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