Created
December 23, 2016 00:04
-
-
Save gasi/a6e39484fd30e61d7e4b037e65a26525 to your computer and use it in GitHub Desktop.
Type-safe Redux
This file contains hidden or 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
interface BasicAction<T> { | |
type: T | |
} | |
interface PayloadAction<T, P> extends BasicAction<T> { | |
payload: P | |
} | |
interface ErrorAction<T> extends BasicAction<T> { | |
error: Error | |
} | |
type PayloadErrorAction<T, P> = PayloadAction<T, P> & ErrorAction<T> | |
type ActionA = BasicAction<'ACTION_A'> | |
type ActionB = PayloadAction<'ACTION_B', {foo: string}> | |
type ActionC = PayloadErrorAction<'ACTION_C', {bar: number}> | |
type Action = ActionA | ActionB | ActionC | |
const reducer = (state: any, action: Action) => { | |
switch (action.type) { | |
case 'ACTION_A': | |
// console.log(action.payload) // FAIL! | |
// console.log(action.error) // FAIL! | |
break | |
case 'ACTION_B': | |
console.log(action.payload.foo) | |
// console.log(action.error) // FAIL! | |
break | |
case 'ACTION_C': | |
console.log(action.payload.bar) | |
console.log(action.error) | |
break | |
default: | |
break | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment