TIL — Typescript type guards and predicates
<p>n TypeScript, type guards are a way to provide additional type information at runtime, making your code more type-safe and reducing the possibility of runtime errors. They help ensure that you are working with the correct type of value, enabling you to perform operations specific to that type with confidence.</p>
<p>Let’s examine a clear example to understand how type guards work. In this example, we have a custom type <code><strong>Foo</strong></code> and a function <code>isValidItem</code> that serves as a type guard for the <code><strong>Foo</strong></code> type:</p>
<pre>
type Foo = 'bar' | 'baz';
const isValidItem = (x: any): x is Foo => {
return typeof x === 'string' && (x === 'bar' || x === 'baz');
};
const item: any = 'bar';
if (isValidItem(item)) {
item;
}</pre>
<p>Let’s break down the example step-by-step:</p>
<ol>
<li><strong>Defining a custom type:</strong> We define a custom type <code><strong>Foo</strong></code> as a union of two string literal types, 'bar' and 'baz': <code><strong>type Foo = 'bar' | 'baz';</strong></code>.</li>
<li><strong>Creating a type guard function:</strong> We declare the <code>isValidItem</code> function with a single parameter <code><strong>x</strong></code> of type <code><strong>any</strong></code>. The function uses a type predicate <code><strong>x is Foo</strong></code> to indicate that if it returns <code><strong>true</strong></code>, <code><strong>x</strong></code> is of type.</li>
<li><strong>Checking the type:</strong> The function body checks if <code><strong>x</strong></code> is a string and if it's either 'bar' or 'baz'. If either condition is met, it returns <code><strong>true</strong></code>, meaning that <code><strong>x</strong></code> can be considered of type <code><strong>Foo</strong></code>:</li>
<li><strong>Using the type guard:</strong> We use the <code>isValidItem</code> function as a type guard in the <code><strong>if</strong></code> statement: <code><strong>if (isValidItem(item)) { ... }</strong></code>. If the condition is true (i.e., <code><strong>isValidItem(item)</strong></code> returns <code><strong>true</strong></code>), TypeScript knows that within this block, the <code><strong>item</strong></code> variable is of type <code><strong>Foo</strong></code>.</li>
<li><strong>Safely using the variable:</strong> Inside the <code><strong>if</strong></code> block, we can safely use the <code><strong>item</strong></code> variable as a value of type <code><strong>Foo</strong></code> without any type errors.</li>
</ol>
<p><a href="https://medium.com/@AbbasPlusPlus/til-typescript-type-guards-and-predicates-1ed69cb1ed21">Website</a> </p>