Using them in ionic, ngrx/store
Here at [arraydigital] we’re using the ionic framework to create some of our mobile apps. I spent some time recently adding ngrx/store to one of our ionic projects and it gave me my first opportunity to see union types in the wild.
A union type is one of the advanced types in TypeScript. It describes a value that can be one of several types. So number | string
is a type that can be either a number
or a string
. It is important to remember that a union type value will have only the members that are in common with the rest of the types in the union.
My first meeting with union types was using ngrx/store actions and reducers. Here are some simple actions from one of our ngrx/store applications. In the last line of the module: export type Actions = LoadAction | LoadSuccessAction
, is where the first union type is created.
import { Action } from ‘@ngrx/store’;
import { Rate } from ‘../models/models’;
import { type } from '../util';
export const ActionTypes = {
LOAD: type(‘LOAD’),
LOAD_SUCCESS: type(‘LOAD_SUCCESS’)
}
export class SetAction implements Action {
readonly type = ActionTypes.LOAD;
}
export class LoadAction implements Action {
readonly type = ActionTypes.LOAD_SUCCESS;
constructor(public payload: Rate[]) {
}
}
export type Actions = LoadAction | LoadSuccessAction;
This pattern is common in all of our actions. The union type gives us a type safe action.type
to switch on in our reducers. In the reducer example below we can also define the action parameter to the reducer function as union type Rate.Actions | Rates.Action
. This effectively creates a union of unions.
export function reducer(
state: State, action: Rate.Actions | Rates.Actions): State {
switch (action.type) {
case Rates.ActionTypes.LOAD: {
const rates = action.payload;
// return new state
}
case Rates.ActionTypes.LOAD_SUCCESS: {
const rates = action.payload;
// return new state
}
case Rate.ActionTypes.SELECT: {
const rate = action.payload;
// return new state
}
default: { return state; }
}
}
I have just scratched the surface of union types and there will be many more uses that we’ll see as we continue to develop with TypeScript. Until then, I’d be interested in hearing about how you are using them in the wild.