7 Secret TypeScript Tricks Pros Use
<h1>1. Type Inference</h1>
<p><strong>Typescript</strong> is smart enough to <strong>infer the data types</strong> when you help it narrow them down.</p>
<pre>
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;
}
}</pre>
<p>As shown above, <strong>TypeScript</strong> infers the type of the action based on the <code>type</code> property, so you DON'T need to check whether <code>payload</code> exists.</p>
<p><a href="https://medium.com/@tapajyoti-bose/7-secret-typescript-tricks-pros-use-3080d4d1e972"><strong>Read More</strong></a></p>