7 Secret TypeScript Tricks Pros Use

<h1>1. Type Inference</h1> <p><strong>Typescript</strong>&nbsp;is smart enough to&nbsp;<strong>infer the data types</strong>&nbsp;when you help it narrow them down.</p> <pre> enum CounterActionType { Increment = &quot;INCREMENT&quot;, IncrementBy = &quot;INCREMENT_BY&quot;, } 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 // &amp; has no payload return state + 1; case CounterActionType.IncrementBy: // TS infers that the action is IncrementByAction // &amp; has a number as a payload return state + action.payload; default: return state; } }</pre> <p>As shown above,&nbsp;<strong>TypeScript</strong>&nbsp;infers the type of the action based on the&nbsp;<code>type</code>&nbsp;property, so you DON&#39;T need to check whether&nbsp;<code>payload</code>&nbsp;exists.</p> <p><a href="https://medium.com/@tapajyoti-bose/7-secret-typescript-tricks-pros-use-3080d4d1e972"><strong>Read More</strong></a></p>
Tags: TypeScript