Member-only story
7 Secret TypeScript Tricks Pros Use ππ€«
4 min readMay 14, 2023
TypeScript is an outstanding tool to make our lives easier & avoiding bugs, yet sometimes feels overwhelming to use.
This article outlines 7 TypeScript tricks that will make your life easier which all pros use.
1. Type Inference
Typescript is smart enough to infer the data types when you help it narrow them down.
enum CounterActionType {
Increment = "INCREMENT",
IncrementBy = "INCREMENT_BY",
}
interface IncrementAction {
type: CounterActionType.Increment;
}
interface IncrementByAction {
type: CounterActionType.IncrementBy;
payload: number;
}
type CounterAction =
| IncrementAction
| IncrementByAction;
function reducer(state: number, action: CounterAction) {
switch (action.type) {
case CounterActionType.Increment:
// TS infers that the action is IncrementAction
// & has no payload
return state + 1;
case CounterActionType.IncrementBy:
// TS infers that the action is IncrementByAction
// & has a number as a payload
return state + action.payload;
default:
return state;
}
}