Skip to content

Instantly share code, notes, and snippets.

@gasi
Created December 23, 2016 00:04
Show Gist options
  • Save gasi/a6e39484fd30e61d7e4b037e65a26525 to your computer and use it in GitHub Desktop.
Save gasi/a6e39484fd30e61d7e4b037e65a26525 to your computer and use it in GitHub Desktop.
Type-safe Redux
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