<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tar Viturawong on Medium]]></title>
        <description><![CDATA[Stories by Tar Viturawong on Medium]]></description>
        <link>https://medium.com/@tar.viturawong?source=rss-2c3699b38217------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*45OS7UGRWUt-7xU-K1Hm9w.jpeg</url>
            <title>Stories by Tar Viturawong on Medium</title>
            <link>https://medium.com/@tar.viturawong?source=rss-2c3699b38217------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:28:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tar.viturawong/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Casting (and Non-Casting!) in TypeScript]]></title>
            <link>https://medium.com/@tar.viturawong/casting-and-non-casting-in-typescript-608e23e19e9c?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/608e23e19e9c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 05:18:30 GMT</pubDate>
            <atom:updated>2023-03-08T05:18:30.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xqAmT1mvnIplps50" /><figcaption>TypeScript Casting: It’s mostly about perspective. Photo by <a href="https://unsplash.com/@iam_anih?utm_source=medium&amp;utm_medium=referral">Anika Huizinga</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Type casting — the act of converting the type of a value to another type— is an operation every learning programmer of a typed language will encounter at some point.</p><p>The concept, in a nutshell, is telling our computer program to change a representation of a value to a related representation so that different operations can be done on or with it. It’s telling compiler things like: “<em>Hey there, I have a cat in this variable, but please treat it generically like an animal</em>.” Or, “<em>Hey there, this cat is actually a kitten, I promise. You can crash on me afterwards if it’s not</em>.” Sometimes, it’s “<em>Hey there, this cat here, she’s tiger-y enough to be a tiger. Treat her like a tiger. It’s unsafe but whatevs</em>.” The compiler may then needs to make sure that the needed internal re-representation takes place. As you can imagine, some of these re-representations are safe; others, not so safe.</p><p>Now, TypeScript, doesn’t really “cast” types in that same sense. After all, <a href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#goals">nothing happening in the type universe is supposed to change any underlying JavaScript</a>! Rather, that casting is for us (silly humans!) to be more expressive about the types we throw around. In this article, we will look at different ways to convert types in TypeScript.</p><h3>Primer: The type hierarchy</h3><p>We will touch on the most basic concept of type theory: Types form a hierarchy. Take our animal-cat-kitten-tiger example. Every kitten is a cat, but not every cat is a kitten. This makes <em>kitten</em> a “narrower” type, or a <strong>subtype </strong>of <em>cat</em>. Stated the other way, the type <em>cat</em> is the “wider” type, or a <strong>supertype</strong> of <em>kitten.</em></p><p>To state the “all <em>X</em>s are <em>Y</em>” is to state that <em>X</em> is a subtype of <em>Y</em>.</p><p>Intuitively, going from a subtype to a supertype, you lose specificity. Going from a supertype to a subtype, you gain specificity, which will be either asserted, guarded, or just unsafely presumed.</p><p>In TypeScript land, arrays and functions are subtypes of object. String literals — like &quot;onmessage&quot; — are subtypes of strings. Every component of a union is a subtype of that union. Every component of an intersection is a supertype of that intersection.</p><p>That’s enough. Let’s go.</p><h3>Type widening in TypeScript</h3><p>Type widening is when you re-represent a value’s type as its supertype—from our metaphorical<em> kitten</em> to <em>cat</em>. To do it safely, simply assign the value to a variable as a super type.</p><pre>interface Cuddlies {<br>  cuddle(): void;<br>}<br>interface Cat {<br>  cuddle(): void;<br>  meow(): void;<br>}<br>const banoffee: Cat = {<br>  cuddle: () =&gt; alert(&quot;yay I love cuddles!&quot;),<br>  meow: () =&gt; alert(&quot;meow!&quot;)<br>};<br>const cuddlyBanoffee: Cuddlies = banoffee; // safe &lt;3</pre><p>(<a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HkNjUxkPcIAhS2tbezRZfCIXCysbOy5kAHoR5AI4W2QAHgBmIA">playground link here</a>)</p><p>You widen a type when you decide that the subtype details are no longer needed for that value, and that TypeScript will aid you more helpfully with those details abstracted away. It’s a tool for simplicity.</p><p>Even though type widening is theoretically safe, there is one TypeScript-specific behavior that you should be aware of:</p><h4>An object literal cannot have more properties than the type it’s being assigned to</h4><pre>const cuddlyBanoffee: Cuddlies = {<br>  cuddle: () =&gt; alert(&quot;yay I love cuddles!&quot;),<br>  meow: () =&gt; alert(&quot;meow!&quot;)<br>}; // actually safe, but not allowed!</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=18&amp;pc=38#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HkNjUxkPcIAhS2tbezRZfCIXMjdZTu8-AKCyyOi4hKTG1Kqcigr85GHisbClqprkAHodgIQwdECcaII4WyzkM3RJK0kTzQhMNKA">playground link here</a>)</p><p>Why does TypeScript do this?</p><p>Unlike our prior example of banoffee which we may use in other places expecting exactly the Cat type, the object literal being directly assigned to cuddlyBanoffee cannot possibly be directly assigned anywhere else. And because meow() will not be accessible from the Cuddlies interface, this property is now useless, so TypeScript presumes we made a mistake.</p><p><em>Type widening loses specificity.</em></p><p>TypeScript <a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HlJMCAQcOCgUGHQQBDBgY2QCCBBMAEEMD3DaFJxwh1l8AkKdJQE+geHZMbI3WXtkbz8AoLLI6LiEpJkPQiqcigr8ncK9kuCw26q+ei5kAHovgM70QKTXpwWxZZBmdCSKySQGaCCYNJAA">will also stop you</a> from doing the same to a function expecting just Cuddlies as an argument.</p><h4>A useful identity function</h4><p>In the example above, type widening will happen automatically upon assigning a value to a type-annotated variable declaration, or passing it as an argument to a function. However, once in a while, you need to widen the type and you don’t want to bother with setting a temporary variable.</p><p>The following function can come in handy:</p><pre>function widen&lt;T&gt;(value: T) {<br>  return value;<br>}</pre><p>The function is an <strong>identity</strong> function, it does nothing except returning the argument. Because type widening happens automatically when you pass a value as a function argument, you can call this function and specify your target type, and voila, it returns the argument widened to type T.</p><p>When might you need this? If you are forming an expression that needs to satisfy a complex union type. Sometimes TypeScript gives quite cryptic and overwhelming errors when it cannot match a value to a type that has a lot of union components. You made one mistake, you don’t know where, and suddenly you are getting a TypeScript error that highlights an huge block. (If you’ve ever edited an <a href="https://swagger.io/specification/">OpenAPI specification</a> in TypeScript, you’ll know what I’m talking about.)</p><blockquote>Some may argue that if your expression is complex then you should break it down into variables and compose them. It’s true a lot of times, but not always. Authoring an in-code JSON so that it checks with TypeScript is one case where you prefer the JSON to stay intact.</blockquote><p>This is what you can do to narrow down the error. You can go into each complex sub-expression and apply widen to it with your expected type. If the expression is not a subtype of the type you claim it to be, TypeScript will give you a more digestible error. Likewise, if the type you give to widen is not what the containing expression expects of that sub-expression, TypeScript may also give you a more digestible error. You can nest this strategy and apply a divide-and-conquer method, and diagnose your type issue with their expressions <em>in place</em>.</p><h3>Type narrowing in TypeScript</h3><p>Going from <em>cat</em> to <em>kitten — </em>from supertype to subtype — is known as type narrowing.</p><p>The central concern in down-casting is to make sure that the new perspective is accurate. Not every animal is a cat, and not every cat is a kitten. Not every object is a function.</p><p>The easiest but dangerous way to down-cast is to use the as operator:</p><h4>The “as” operator</h4><pre>interface Cuddlies {<br>  cuddle(): void;<br>}<br>interface Cat {<br>  cuddle(): void;<br>  meow(): void;<br>}<br>const banoffee: Cat = {<br>  cuddle: () =&gt; alert(&quot;yay I love cuddles!&quot;),<br>  meow: () =&gt; alert(&quot;meow!&quot;)<br>};<br>const cuddlyBanoffee: Cuddlies = banoffee; // safe &lt;3<br>// This is not allowed, it&#39;s theoretically unsafe!<br>const cuddlyBanoffeeIsACat: Cat = cuddlyBanoffee;<br>// To insist that it&#39;s safe, do this:<br>const cuddlyBanoffeeReallyIsACat = cuddlyBanoffe as Cat;</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=21&amp;ssc=58&amp;pln=1&amp;pc=1#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HkNjUxkPcIAhS2tbezRZfCIXCysbOy5kAHoR5AI4W2QAHgBmATHkABUAC2AiDeQrSUCEjQhMLORgMAByIjBV9SgIMGAEPej0EymINLqTSRScFrbBiAxAgAQUcDgkPkauD+Aw6tSWyzYJxMG0kVwhpwuEzex0wSKuG0YnwaPxh7TsACUIE8gaCIS5Sa1YXYAkRHFwgA">playground link here</a>)</p><p>Changing a Cuddlies to a Cat is a narrowing cast because not all cuddlies meow. As such, cuddlyBanoffee can’t be assigned to the type Cat — an assignment requires an widening cast or an exact match. The as operator performs the narrowing, and cuddlyBanoffeeReallyIsACat is now type Cat.</p><p>From our little snippet it’s obvious that this specific narrowing would have been practically OK; after all we’re just assigning and re-assigning variables. However, in most real-life cases where you will be tempted to use the as operator, such safety may not be so obvious, or it may actually be unsafe! It is up to you to make it obvious by other means that the cast is safe. And as with anything that requires manual knowledge management (= more maintenance cost), do at least consider alternatives.</p><p>The alternatives? Type guards and assertions, and — if possible —consider restating your types.</p><h4>Safe(r): using guards and assertions</h4><p>Instead of doing this:</p><pre>declare const someValue: object;<br>console.log((someValue as Array).length);</pre><p>You can remove the need for as by using the guard Array.isArray()</p><pre>declare const someValue: object;<br>if (Array.isArray(someValue)){<br>  console.log(someValue.length);<br>}</pre><p>The Array.isArray() guards someValue such that is type within the if block is now any[] (<a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=21&amp;pc=58#code/CYUwxgNghgTiAEYD2A7AzgF3mpBbEAalBAK4gBc8SARgFbgYDcAUAJYBm8AFAIIwxQAngDpWaPgMFcc+IqRABKBQG9m8RKhwQQwiEgDm0vIWJldIFPowALBSwC+QA">see playground</a>). This is safer, because the its in the block is relevant only if the runtime execution of its condition is true.</p><p>TypeScript’s type guards allow you to define a runtime definition that would imply that that a certain type can be satisfied.</p><p>This is how Array.isArray’s type is defined:</p><pre>(arg: any) =&gt; arg is any[];</pre><p>The part arg is any[] is what defines this function as a <em>guard. </em>It is essentially a boolean type with the extra meaning that, when the return value is true, TypeScript should regard arg as type any[].</p><p>We can make our own guard that will allow a cast from Cuddlies to Cat too:</p><pre>function isCat(cuddly: Cuddlies): cuddly is Cat {<br>  return typeof (cuddly as Cat).meow === &quot;function&quot;;<br>}</pre><p>And then use it:</p><pre>if (isCat(cuddlyBanoffeeIsACat)) {<br>  cuddlyBanoffeeIsACat.meow(); // now &quot;safely&quot; a Cat<br>}</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=24&amp;ssc=1&amp;pln=21&amp;pc=1#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HkNjUxkPcIAhS2tbezRZfCIXCysbOy5kAHoR5AI4W2QAHgBmATHkABUAC2AiDeQrSUCEjQhMLORgMAByIjBV9SgIMGAEPej0EymINLqTSRScFrbBiAxAgAQUcDgkPkauD+Aw6tSWyzYJxMG0kVwhpwuEzex0wSKuG0YghgyFoG0ctB+MPadiBoIk9EKZDcsmpALpjgAdBUtPRhksrBoAmgJHwBDAXgh7sYTgQKVSHN1CAoqbKRZJmchbmB0FAQMgwOEAA7qEmU1kBIiOejcvI+JwuUISkBS4DGUL6IA">playground link here</a>)</p><p>How safe is this? In fact, <em>for one usage instance it is actually no safer</em>: you still need to presumptively narrow cuddly into Cat for TypeScript to allow its meow to be accessed so that we can check that it’s a function. But the more you use this guard in other places, the safer it will become compared to ad-hoc down-casting with as everywhere. Why? It’s because your check is now consistent. If more run-time checks are needed later, you implement them in this one place.</p><p><em>The good news is, as far as I am aware, all </em><a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types"><em>built-in TypeScript type guards</em></a><em> are safe.</em></p><p>Type assertions are cousins of type guards. Instead of using them conditional branches, we use them to throw exceptions. We can create one like this:</p><pre>function assertCat(cuddly: Cuddlies): asserts cuddly is Cat {<br>  if (typeof (cuddly as Cat).meow !== &quot;function&quot;) {<br>    throw Error(&quot;Not a cat&quot;);<br>  }<br>}</pre><p>In the same way that TypeScript assumes we correctly implement the predicate logic for the type guard, here it also assumes that we correctly choose the condition to throw an exception.</p><p>We can then use the assertion like so:</p><pre>// will throw exception if not a cat<br>assertCat(cuddlyBanoffeeIsACat); <br>cuddlyBanoffeeIsACat.meow(); // now a Cat</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=22&amp;ssc=42&amp;pln=21&amp;pc=1#code/JYOwLgpgTgZghgYwgAgMIFcAmmA2wIDOyA3gFDLIJa4QAUAlAFzIBuA9sJgNykC+ppUJFiIUqOGBLlK1HHSasO3aQFsIbAO4Nm7Tj36kEbEAUkAjOCDYwYECM3GSAvFIpVsc5g2ROAfMjg5KDBaACIATzhw5ABJZBw2FhR3GgIAQlD6ABpVdQ0veh9-QOgQ0LVNDPo+HkNjUxkPcIAhS2tbezRZfCIXCysbOy5kAHoR5AI4W2QAHgBmATHkABUAC2AiDeQrSUCEjQhMLORgMAByIjBV9SgIMGAEPej0EymINLqTSRScFrbBiAxAgAQUcDgkPkauD+Aw6tSWyzYJxMG0kVwhpwuEzex0wSKuG0YpDgBAIpUctB+MPadiBoIk9B4VNasNpIMcADoKlpGaNxlYNAE0BIBDAXgh7sYAqTyRJKbJwg5uoQFCSycEiFSTkRHK4TjBkLQwOEAA7qA3yprS4VgehcvLINJOFyhMUgCXAYyZPUUK5QTTIACiUH9UDCADk2LtKBJMjwKPxeEA">playground link here</a>)</p><h4>Safe: classes</h4><p>If your project embraces OOP, classes and inheritance can be a good alternative to alleviate you from potentially unsafe casting in some cases. This works because classes come with their own runtime guards, namely the instanceof operator.</p><pre>abstract class Cuddlies {<br>  abstract cuddle(): void;<br>}<br>class Cat extends Cuddlies {<br>  meow(){ /*...*/ };<br>  cuddle(){ /*...*/ };<br>}<br>declare const cuddlyBanoffee: Cuddlies;<br>if (cuddlyBanoffee extends Cat){<br>  cuddlyBanoffee.meow();<br>}</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=11&amp;pc=2#code/IYIwzgLgTsDGEAJYBthjAgwgVwCa+QEsBTDAbwCgEFRIZ4k8DiAKASgC4EA3Ae0NwBuCgF8KKNBkzBExAB4RiAO1xSmRUgkrUAtsV4B3dmQQB6AFQA6a+dMIRw6rHWs2Ji9cu37wsbmISUMRIvEqQjPjIAJ4AQsBKvABmicTEXDiRJGDChIkILM6RsfFJKcGEYRDxsPp50hBuVBEExQnJqZZ6huy+QA">playground link here</a>)</p><p>However, OOP introduces many conceptual constraints that may not be ideal with the way you think about your project, so balance the benefits and downsides accordingly.</p><h4>Discriminated union</h4><p>If the design of your application allows for this, consider structuring your types that need to be discriminated such that they can be expressed as discriminated unions.</p><p>To make this more sense to our example, we need to up our example’s complexity slightly and have another cuddly-compatible interface: Dog.</p><pre>interface Cat {<br>  species: &quot;Cat&quot;;<br>  cuddle(): void;<br>  meow(): void;<br>}<br>interface Dog {<br>  species: &quot;Dog&quot;;<br>  cuddle(): void;<br>  bark(): void<br>}<br>type Cuddlies = Cat|Dog<br>declare const cuddlyBanoffee: Cuddlies;<br>if (cuddlyBanoffee.species === &quot;Cat&quot;){<br>  cuddlyBanoffee.meow();<br>}</pre><p>(<a href="https://www.typescriptlang.org/play/?ssl=1&amp;ssc=1&amp;pln=15&amp;pc=2#code/JYOwLgpgTgZghgYwgAgMJzMg3gKGcgZwAcIFgICAuZAInTBoG49kEBXAEw4BsIAKAJTUAbgHtgHZvgC2EUQHdBI8ZJwBfHKEixEKACKiA5thbFS5KrQOGmLdl15LkYiVOQAjOFADWTlx3UcMABPEjROHgtkAF40DAAfaxwOUm4vFARREAJMex5ggCE4EFEYGAgIalQI7gtmYBhkPjzuQuLS8ogAOjMyChjo2LoMGgFcfBa2krKKrtkFQWY1IA">playground link here</a>)</p><p>With discriminated unions, you can go back to use TypeScript’s safe built-in type guards. However, this time, note that we have now inverted how we relate Cat and Cuddlies: the interface that’s common between Cat and Dog is now what defines Cuddlies.</p><h4>When TypeScript won’t let you &quot;as&quot;-cast</h4><p>If the type you try to cast to isn’t a subtype or supertype of your current expression, you will get an error when you attempt to cast with as:</p><pre>declare const foo: string;<br>const bar = foo as number; // nope</pre><blockquote>Conversion of type ‘string’ to type ‘number’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown’ first</blockquote><blockquote>— TypeScript compiler</blockquote><p>There might be a technical reason why you might get this error in what you think is a sensible cast, and it will have something to do with your understanding of type relationship is misaligned with the TypeScript compiler’s understanding. Generics and keyof operators are some of the places where this may crop up.</p><p>As stated in the error, you can always choose to override this by first widening to unknown (the “top” type — the supertype of everything — the most generic and featureless of them all), and then narrowing it to the type you want. This, as with all type narrowing, is potentially unsafe. Before you do that though, re-inspect the type relationship; are you making a cat out of a banana?</p><h3>Non-casting: the “satisfies” operator</h3><p>TypeScript 4.9 includes a new <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator">satisfies operator</a> that, similar (but distinct) to our custom widen function, can type-check an expression in its place. The difference is that satisfies will not attempt to widen the type of your value.</p><p>This is useful if you just want to check your value against an expected supertype, but the specific structures (including exact literals) in your value must also be preserved in its type, for example, for later access or for aiding generic type argument inference.</p><pre>enum DeviceType {<br>  Speaker = &quot;SPEAKER&quot;,<br>  Light = &quot;LIGHT&quot;,<br>  Heater = &quot;HEATER&quot;<br>}<br><br>const DeviceTypeInfo = {<br>  SPEAKER = { type: &quot;speaker&quot;, controls: [&quot;volume&quot;] },<br>  LIGHT = { type: &quot;light&quot;, colors: [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;] },<br>  HEATER = { type: &quot;heater&quot;, kinds: [&quot;gas&quot;, &quot;electric&quot;], automatic: false }<br>} satisfies Record&lt;DeviceType, any&gt;;</pre><p>In the example above, the DeviceTypeInfo use the satisfies operator to make sure that it is a dictionary with all keys from the DeviceType, without forcing the type of each of DeviceTypeInfo’s object property to a type. With this, it will be perfectly legal to access the following property.</p><pre>DeviceTypeInfo.HEATER.automatic</pre><p>Now, one day, a new device type arrives. This satisfies operator will tell you that your DeviceTypeInfo is missing a new type if you only add it to the enum. Now you have the benefits of keeping a detailed type and checking against a super type in one expression.</p><h3>Summary</h3><ul><li>TypeScript offers several ways for us to change our perspective about a value’s structure and capabilities through type narrowing and type widening.</li><li>To widen a type, assign an expression to a variable, or pass it to a function.</li><li>To narrow a type, use type guards such as discriminator comparison, guard functions, and instanceof operator. Use the as operator if you must, but know that it maybe unsafe.</li><li>To check that a value is of an expected type without widening it, use the satisfies operator. You need TypeScript ≥ 4.9.</li><li>Remember that TypeScript types do not affect JavaScript runtime behavior; only actual JavaScript code such as guards can grant you <em>runtime</em> safety.</li></ul><p>Hopefully, these explanations on how to convert between types safely will help improve expressiveness and robustness in your TypeScript projects. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608e23e19e9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting to know and love TypeScript’s “meta” types]]></title>
            <link>https://levelup.gitconnected.com/getting-to-know-and-love-typescripts-meta-types-5e17a8856b17?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e17a8856b17</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 11:19:20 GMT</pubDate>
            <atom:updated>2020-02-18T03:28:58.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yxIBQ03Q6sWDpghv" /><figcaption>Strange phenomena manifest towards the boundary of the nature of things. So it is with the Universe. So it is with TypeScript. Photo by <a href="https://unsplash.com/@kvedula?utm_source=medium&amp;utm_medium=referral">Kamesh Vedula</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As you write more code in TypeScript or use more libraries with TypeScript typing, you will likely become aware of a few types whose meaning can be rather puzzling. Let me throw a few out at you:</p><pre>any<br>void<br>undefined<br>unknown<br>never</pre><p>In my head, I call these types the “meta” types because they often go beyond describing concrete, real-world “things”. Instead, they either surface as part of the language’s technicality, or they can communicate an abstract concept that a TypeScript programmer would do well to heed.</p><p>If the sight of these types has sent your stomach churning in anxiety, read on! In this article, I will try my best to put you at peace with these types, and they shall become your ally!</p><p><em>Disclaimer: Please note that the “meta” designation is completely personal, and as such you might not find it elsewhere. Two of these types — </em><em>unknown and </em><em>never — are also formally known as “top” and “bottom” types in type theory.</em></p><h3>The first pair: “any” and “unknown” types</h3><blockquote><strong>TL;DR:</strong> avoid &quot;any” if you can, but use it if you must.</blockquote><p>The any and the unknown types have — at first glance —a similar practical use: in <em>some</em> way both types allow you to be “vague” about your typing.</p><pre>const a: any = &quot;foo&quot;;<br>const b: unknown = &quot;bar&quot;;</pre><p>You could replace &quot;foo&quot; and &quot;bar&quot; above with anything. And I mean <em>anything</em>. All assignments to variables of type any and unknown are valid, as are all function argument values being provided as an any- or unknown-typed parameters. In this manner, both types behave the same.</p><p>Their first difference lies in the opposite direction. What if you <em>have</em> an any- or unknown-typed value that you attempt to assign to a variable (or supply as a function argument)?</p><pre>const a1: any = &quot;foo&quot;;<br>const a2: string = a1;<br>const a3: boolean = a1; // sure! (!!!)<br>const a4: any = a1;<br>const a5: unknown = a1;</pre><pre>const b1: unknown = &quot;bar&quot;;<br>const b2: string = b1; // nope! (!!!)<br>const b3: boolean = b1; // nope!<br>const b4: unknown = b1;<br>const b5: any = b1;</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=11&amp;pc=20#code/MYewdgzgLgBAhgRgFzzATxgXhgIgGYgg4DcAUKJLHAEwrQBOAlmAOZbwJkXTwDMKAI0IAbAKZww7RF3A84AFhQSM2aeVlUArCgCuYANZgQAd0mrOpdZRgDkMPYZNncAuPRJWeA2jAbM22LYy1gL8NiLizkGesAKK9gZGpuzR3LHaqCo2nEA">playground link here</a>)</p><p>As you can see in the playground, the any value can be assigned to anything, even when it empirically appears to be a value of the “wrong” type (note a3). In this respect, the unknown type is exhibiting a kind of “opposite” behavior: it’s not assignable to anything except for something expecting unknown and any , even for what empirically appears to be a value of the “right” type (note b2).</p><p>Now let’s do something that is a reason TypeScript is awesome: let’s see how these two types fare when subjected to <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types">type guards</a>. Note that neither conditional block below will execute in run-time, and that’s OK.</p><pre>const a1: any = &quot;foo&quot;;<br>if (typeof a1 === &quot;boolean&quot;) {<br>  const a2: string = a1; // nope!<br>  const a3: boolean = a1;<br>}</pre><pre>const b1: unknown = &quot;bar&quot;;<br>if (typeof b1 === &quot;boolean&quot;) {<br>  const b2: string = b1; // nope!<br>  const b3: boolean = b1;<br>}</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=11&amp;ssc=2&amp;pln=1&amp;pc=1#code/MYewdgzgLgBAhgRgFzzATxgXhgIgGYgg4DcAUAJZ4wAUUaADgKYhWJabY4BGhANo3DA4AlDADepGDFCRYcAEwpoAJ3JgA5lngIyUmdHgBmFDxD9BWxGQC+pUvthdkMAK5gA1mBAB3MFu5wyiQUVLQMzFRO7Jym5kKiEnrgBlyKMCpqmthOutLJjsYwsQJ+2Tqk1kA">playground link here</a>)</p><p>Now the two types are behaving the same again. Within each conditional block, our “vague” types are guarded for boolean-ness, and so they become boolean types.</p><p>So, the unknown type is intended to be a safe, assume-nothing-ever type. In that sense, you can be vague in declaring something unknown , but should you wish to meaningfully use the value, you <em>must</em> either use type guards or casts.</p><p>The any type, on the other hand, is essentially the same as turning off typing altogether for that value. As long as the value is not subjected to guards, it’s “anything goes” (geddit? 😅). Using any is essentially telling TypeScript to back off.</p><p>But why would you want TypeScript to back off? Well, the any type is a savior if you are in the process of transitioning a huge code base into TypeScript: it allows for a gradual transition. You start first by giving everything as much correct typing as you can subject to other constraints, and leaving the other values any. Then, as your typing scheme becomes more clear, you drop any in favour of more concrete types. And finally, you switch on noImplicitAny option in your tsconfig.json&#39;s <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html">compilerOptions</a>, which stops TypeScript from assuming any type things whose types it can’t infer without your help.</p><h4>Get away from “any” as soon as you can</h4><blockquote>“ไปไหนมา สามวาสองศอก”</blockquote><blockquote>Translation:</blockquote><blockquote>“where have you been?”</blockquote><blockquote>[Another answers:] “seven meter.”</blockquote><blockquote>— Thai proverb</blockquote><p>If you are well on your way to establishing a rigorous typing system in your code base already, use unknown as a way to be vague and assert your way into the type you want via guards. Better still, see if your vagueness is actually a form of type polymorphism that can be expressed with <a href="https://medium.com/@tar.viturawong/the-true-power-of-typescript-generics-1303d78a1c9a">generics</a>. It is worth iterating again that any represents an <em>untyped</em> situation and you are essentially dealing with plain JavaScript on that value.</p><h3>The second pair: “void” and “undefined” types</h3><blockquote>TL;DR: use “void” to disregard function return values, and “undefined” for the intentional returning of undefined.</blockquote><p>In JavaScript, both void and undefined represent the same idea, i.e. that of the undefined value. A function that “returns void” does not return a value, and if you try to save that non-existent return value, it would be undefined. In JavaScript, a function that “doesn’t return” is not behaviorally different from one that explicitly returns undefined :</p><pre>const a = () =&gt; {};<br>const b = () =&gt; undefined;<br>console.log(a());  // undefined<br>console.log(b());  // undefined</pre><p>So what’s the big deal?</p><p>Well, in TypeScript, there is a void type that is <em>distinct </em>from the undefined type. Look at this:</p><pre>const void1: void = undefined;<br>const undefined1: undefined = undefined;</pre><pre>const void2: void = undefined1;<br>const undefined2: undefined = void1; // nope!</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=6&amp;pc=1#code/MYewdgzgLgBAbiAlgEwIwwLwwK5mQUwDNEx9kBuAKFEllwONLUxzyJLKuvGniWQBMALj4oW9dk1RUavCYzLDWDDshYIU0ykA">playground link here</a>)</p><p>As you can see, you can assign an undefined type to a void type, but not the other way round.</p><p>So why does TypeScript have this distinction when it doesn’t exist in JavaScript? To begin to understand this, we shall look at what TypeScript claims is the type for the following expressions without any type annotation whatsoever:</p><pre>const foo = void 0;<br>const bar = function(){};<br>const baz = bar();</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=3&amp;pc=19#code/MYewdgzgLgBAZiEMC8MBuICWATGAGAbgChRJYAjAQwCcV4BXMYKTcACgEoBvAX2NOgwqALzpVqnAkA">playground link here</a>)</p><p><em>(To the relatively uninitiated, the </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void"><em>expression </em></a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void"><em>void 0 produces the </em></a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void"><em>undefined value</em></a><em>, a pre-ES5 legacy where the </em><em>undefined global variable could be overridden in some browsers; it was a wild and wonderful time!)</em></p><p>If you inspect the playground, you will see that foo has type undefined whereas baz has type void. Therein lies the distinction: In TypeScript, a function that does not explicitly return a value returns void.</p><p>“But void <em>IS </em>undefined, so why split hair over it?” you ask.</p><p>Well, in TypeScript land, there <em>i</em>s a difference! Try the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing">nullish coalescence operator</a> on them:</p><pre>declare const a: void;<br>declare const b: undefined;<br>const aOr42 = a ?? 42; // nope!<br>const bOr42 = b ?? 42;</pre><p>(<a href="https://www.typescriptlang.org/play/?ts=3.8-Beta&amp;ssl=1&amp;ssc=1&amp;pln=14&amp;pc=13#code/CYUwxgNghgTiAEYD2A7AzgF3lAXPAbkgJbADcAUKJLAsulgEZ4CuKoAZkSiGeXZtgDyMACwAmeAF5s8APyz44iv0bDxU+AzkKlQA">playground link here</a>)</p><p>You will find that the void value cannot be coalesced in the way that undefined does. Here you will be warned that a cannot be used in this context: <em>“An expression of type ‘void’ cannot be tested for truthiness”. S</em>oon, you will see that this behavior is consistent with other differences between void and undefined.</p><p>Another practical distinction comes when we try to define a function to fit a certain type.</p><p>Let’s suppose you have to define a callback function, say, to a timer.</p><pre>function delay(callback: () =&gt; void){<br>  setTimeout(callback, 1000);<br>}</pre><p>And now, let’s look at what TypeScript will allow as an argument to callback:</p><pre>delay(() =&gt; alert(&quot;hi!&quot;));<br>delay(() =&gt; prompt(&quot;what&#39;s your name?&quot;));<br>delay(function(){<br>  prompt(&quot;what&#39;s your name?&quot;);<br>});<br>delay(function(){<br>  return prompt(&quot;what&#39;s your name?&quot;);<br>});<br>delay(function(){<br>  return alert(&quot;hi!&quot;);<br>});<br>delay(function(){<br>  return undefined;<br>});</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=18&amp;pc=4#code/GYVwdgxgLglg9mABAEwKYBsCGBPAFBTddAI0wgGsAuRXASkQF4A+RANzhmVoG8AoRRAGdUUACowAtqjggo+QiTLkANIgCMABi20A3LwC+vXmix46jFoVQAnOQCIAFjACEd2ruMYcuc80QAHazgJf3sAdwdMKAByQURsGWtEMEwpAH43DxNvUEhYBDo+AUDg0Nw7CKjY+MTk1NQMj30srzxc6HgwQv5EaxEQayQSkPDImLiEgbr0tz1mvWy28A6Cnh6+qAGkK1typ1cmltNcdvyutYENrcRwNGAYMFRkOd0gA">playground link here</a>)</p><p>Everything above is allowed, even functions that return non-undefined value like that ones that call prompt. Let us now contrast with the same experiment when our callback is instead expected to return undefined:</p><pre>function delay(callback: () =&gt; undefined){<br>  setTimeout(callback, 1000);<br>}</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=20&amp;pc=4#code/GYVwdgxgLglg9mABAEwKYBsCGBPAFBTddAI0wgGsAuRXASkQF4A+RcNYGMVZWgbwChEiAM6ooAFRgBbVHBBR8hEmXIAaRAEYADDtoBufgF9+-NFjx1GLQqgBOCgEQALGAEIHtfaYw5cl5ogADrZwUoGOAO5OmFAA5MKI2HK2iGCYMgD8Hl5mvqCQsAh0AkLBoeG4DlEx8YnJqemoWV6GOT54+dDwYMWCiLZiILZIZWGR0XEJSUMNmR4GrQa5HeBdRXx9A1BDSDb2lS7uLW3muJ2FPRtCWzusYOyc3AsneasXvYtAA">playground link here</a>)</p><p>Now almost everything breaks except for the one function that explicitly returns the undefined value. This is, in fact, the <em>semantic </em>difference between the two types. As a return type, the undefined type requires the function to explicitly return undefined. On the other hand, the void return type just means that the function’s return value <em>is not meaningful and should simply be disregarded</em>. This is important especially for arrow function expressions, because they are capable of implicitly returning the value of their only expression. Putting void as the return type lets TypeScript disregard such an implicit return value.</p><p>To demonstrate this another way, let’s have a look at these callbacks defined on their own and called directly:</p><pre>type Callback = () =&gt; void;</pre><pre>const a: Callback = () =&gt; alert(&quot;hi!&quot;);<br>const b: Callback = () =&gt; prompt(&quot;what&#39;s your name?&quot;);<br>const c: Callback = function(){<br>  prompt(&quot;what&#39;s your name?&quot;);<br>};<br>const d: Callback = function(){<br>  return prompt(&quot;what&#39;s your name?&quot;);<br>};<br>const e: Callback = function(){<br>  return alert(&quot;hi!&quot;);<br>};<br>const f: Callback = function(){<br>  return undefined;<br>};<br>const g: Callback = function(){};</pre><pre>const returnA = a();<br>const returnB = b();<br>const returnC = c();<br>const returnD = d();<br>const returnE = e();<br>const returnF = f();<br>const returnG = g();</pre><p>(<a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=26&amp;pc=21#code/C4TwDgpgBAwghgGwQIzgYwNZQLxQBQCUOAfFAG4D2AlgCYDcAUA2hQHYDOwUcAXLIinRZchEtwQQATsDwAiABZUAhLIKMWHLsj7wkqTDnxFspMJIoBbMDNkB3eXGABydlBAUArpKis4FiAD8qupsnFBoOgL6wlAAZh6saMBUbIQA3gxQUGaW1nL2ji5unt6+-kFqDAC+IZpQNJF6QobxicmpBBlZkhDAXqzZ5lY2Bc6u7l4+foHB1bVhEI2CBritSSms6ZlQPX2SA4hSNooqlTXMoVyxS9EtCesdXTu9-VAJNBCxVKwQ9HMXdQA5jdmqt7u1Np1-gCwrt+gBBQxwQjzLhw-YAIUMyBRMLRL32MEMaFxGlhBNYABFDDRSZdnntWABRQwQOl1dGsABiLXZ5MZAHFDICUUA">playground link here</a>)</p><p>See that regardless of what the function implementations return, when we actually evaluate these functions, TypeScript will disregard their return values and we end up with void in all cases.</p><p>Note though, that in JavaScript-land which TypeScript eventually transpiles to, the return values are intact (so above returnB and returnD may have a concrete value). TypeScript only stops you from consuming it in compile-time. The effect is that you can “sloppily” return a value without intending to make it meaningful (again, arrow functions!), and TypeScript will help make it harder to consume such a value.</p><h4>Are you returning emptiness, or are you not returning?</h4><p>If it had not been for built-in ES6 features such as Map and WeakMap, whose getters can return undefined, I would have argued that one should treat undefined and null identically to mean a missing value, rather than having subtly different degrees of emptiness. Debating this, however, risks sparking a religious war and so I will humbly submit to disagreement, as it is not pertinent here.</p><p>What <em>is</em> pertinent here is that if you do use undefined as a return value, use the undefined type for it and use void to annotate functions whose return value <em>carry no meaning</em>. This distinction is especially important if your function conditionally returns undefined <em>or</em> <em>otherwise </em>some concrete value, as is the case with the ES6 Map getter. The practical benefit is that you will be protected against accidental consumption of a return value that is not supposed to be consumed.</p><h3>The “never” type</h3><p>Out of all the meta-types, the never type is perhaps the most curious; it also represents a useful concept and has uses in many — although seemingly disconnected — situations.</p><p>The never type is an example of what type theory calls a “bottom” type, a type that contains no possible instance (that’s my limited understanding anyway, I’m no type theorist!). In TypeScript it denotes the idea of impossibility or non-applicability. Let’s look at some of the situations where this happens:</p><h4>Control flow that prevents return/yield</h4><p>Consider these functions:</p><pre>function gameLoop(): never { <br>  while (true) {}<br>}</pre><pre>function die(): never { <br>  throw Error(&quot;boo hoo&quot;); <br>}</pre><p>The function gameLoop does not return at all because there is an infinite loop inside it. This function can have its return type declared as never. (Note though this is likely not a realistic function in typical JavaScript-land, see my footnotes at the end of this piece.)</p><p>The function die does not return in a normal way and instead throws an exception. Likewise, this function can have its return type declared as never. Here, never is a consequence of control flow making the act of returning impossible, thereby rendering the return value non-applicable.</p><p>The never type annotation is useful in this case because it can indirectly alert you of unreachable places.</p><pre>const afterlife = die(); // type never<br>// because its assignment is unreachable</pre><p>Analogous to these are <a href="http://www.typescriptlang.org/play/index.html#code/GYVwdgxgLglg9mAVAAjAUwG5oE4E0ZoA2AJgM4AUAlMgN4C+QA">generators that never yield</a>.</p><blockquote>Here’s a riddle: can an async function’s return type be “never”?</blockquote><h4>Narrowing into impossibility</h4><p>I’m fascinated by a form of ancient Indian logic called <a href="https://en.wikipedia.org/wiki/Catu%E1%B9%A3ko%E1%B9%ADi">Chatuskoti</a>. In the Buddhist <em>suttas, </em>it is common to see a proposition set out four-fold such as: <a href="https://www.accesstoinsight.org/tipitaka/mn/mn.063.than.html">“Is the Universe finite? Is it infinite? Is it both finite and infinite? Is it neither finite nor infinite?”</a> To these ancient folks, it seemed that a binary question can expand into a four-fold truth value. If you answer “no” to all of these possibilities, you end up in an impossible situation.</p><p>We can model such logic like in TypeScript too:</p><pre>enum FourFoldTruthValue {<br>  Yes,<br>  No,<br>  Both,<br>  Neither<br>}</pre><pre>function answerQuestion(answer: FourFoldTruthValue)<br>{<br>  if (answer === FourFoldTruthValue.Yes){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.No){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Both){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Both){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Neither){ /* ... */ }<br>  else {<br>    // what is the type of `answer` here?<br>  }<br>}</pre><p>(<a href="http://www.typescriptlang.org/play/index.html#code/KYOwrgtgBAYg9mATvANgEwCqLAFwBYBqAhimMAN4BQUUAmsAM4A01UAcnCzQEJz5ftgAS3zBElAL6VKAMzAgAxjiFwQUIiAYB3MQEUyDZaoAUG7WIBcsBMjjosuQiTIBKSlRpCZUU5p2IoAF5g6yRUTGx8YlJgADp6BhdyKAB6ACooWKyoNJSoKRpgFAZgKC8fM38gkPgwuwjHaLJYjiTUjKzYnLyCqCKSsu9fcwDgwNDbe0inGNjefDb0zOzc-NZ+0vLhqrGJ8Ico5zi2YVFERY6VnvXi0o8aVLytPCIcMoYoUU+ATwAHUrg3gABpUxECoHgxMAAPysGig8Q0KQSIA">playground link here</a>)</p><p>The type of answer in the final else branch is never. Why? answer must be one of the four possible enum values, and since each of the if clauses successively weeds out each remaining possibility, in our final else clause, we have no possibility left. Thus the type is never.</p><p>Narrowing into imposibility is common when you need to completely handle different possibilities. Can you think of how we can leverage TypeScript to ensure our function’s integrity that, should more possibilities be added to it (for instance, if we go to a hypothetical five-fold truth value?), that we shall be warned of unhandled cases?</p><p>You can do so with this nifty little function, which you can adapt to your needs:</p><pre>function unreachable(neverValue: never){<br>  return Error(&quot;Never get here&quot;);<br>}</pre><p>Now, in our function where we need to handle all cases, we call this function at the bottom:</p><pre>function answerQuestion(answer: FourFoldTruthValue)<br>{<br>  if (answer === FourFoldTruthValue.Yes){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.No){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Both){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Both){ /* ... */ }<br>  else if (answer === FourFoldTruthValue.Neither){ /* ... */ }<br>  else {<br>    throw unreachable(answer);<br>  }<br>}</pre><p>TypeScript will only allow this if answer has type never at the context of calling. never is only assignable to itself. As soon as you add a new possibility not yet handled, your answer type will no longer be narrowed into never , and that call to unreachable will be invalid. Error caught at compile-time! (See examples <a href="http://www.typescriptlang.org/play/index.html?ssl=1&amp;ssc=1&amp;pln=31&amp;pc=2#code/KYOwrgtgBAYg9mATvANgEwCqLAFwBYBqAhimMAN4BQUUAmsAM4A01UAcnCzQEJz5ftgAS3zBElAL6VKAMzAgAxjiFwQUIiAYB3MQEUyDZaoCMACg3axALlgJkcdFlyESZAJSUqNITKjnNOohQALyhtkiomNj4xKTAAHT0DG7kUAD0AFRQ8TlQGWlQUjTAKAzAUD5+FoEhYfARDlHOsWTxHCnpWTnxeQVFUCVlFb7+lkGhweH2jtEucfG8+B2Z2bn5hayD5ZWjNRNTkU4xrglswqKIy11rfZul5V40UPiIcFpQ8ojARAp4RABGKGAuzEbgA3KwpFJZPIlCo1NU9AYjCAAEwgxA2erTJrHOIeR47RHjOp2Q6zFoJJJXVY9db9LbDKoBMS1SbY8nNE5tOA07q9DbFe5MjFsg6NI5zVqLPB8m6CgbCx40F5vD4gL4-P6A4HE8GQyTSOSKFHqzW-AFA0wgYAANzElJsNvtlygjy+OCQagAoohXohTAAiM4uqAAc2AOCgeDEwEDHgkQA">here</a>)</p><h4>Combining mutually exclusive types</h4><p>TypeScript has the <a href="https://medium.com/@tar.viturawong/a-note-on-typescript-non-null-assertion-operator-bad8fbe62bba">non-null assertion operator</a> that lets you ignore the null aspect of a value that maybe null or concrete. For example:</p><pre>declare const foo: string|null;<br>const concreteFoo = foo!; // concreteFoo is type string</pre><p>As I noted in the linked article, there is a curious expression, namely null!, and its type is never.</p><p>Now, why would you want to write such ridiculous nonsense?! A recurring theme here is that while something seems useless on its own, it can make part of a useful composition. Consider this case:</p><pre>someArray<br>  .map(item =&gt; {<br>    const something = /* ... something to do with item */<br>    return something.x ? something.y : null!<br>  })<br>  .filter(Boolean)</pre><p>The result will be an array whose element type is the same as something.y. This works because null! is type never, and the never type disappears when it unions with another concrete type. (It’s like this: to say that there are two possibilities and one of them is impossible is to say that there’s <em>one</em> possibility.) Assuming that something.y can be filtered by truthiness, this map-filter works quite well!</p><p>The above may be considered “dirty” because of our use of null!. In fact, the “type-correct” alternatives would be:</p><pre>someArray<br>  .map(item =&gt; {<br>    const something = /* ... something to do with item */<br>    return something.x ? something.y : null!<br>  })<br>  .filter((item): item is /* ... insert type */ =&gt; Boolean(item));</pre><pre>// or alternatively<br>  .filter(Boolean as (item): item is /* ... insert type */);</pre><p>Problem is, all that guck within filter is essentially the formal augmentation of the Boolean function into a type guard. Guard for which type? Well … the /* ... insert type */ type. Here lies the inconvenience trying to do it the “proper” way: you have to quote the type of something.y. And often when you’re “in the middle of things”, such a type can be a fairly cumbersome expression to write out.</p><p>So using the null! coupled by Boolean filter, we can map-filter an array in a type-safe way, the code looks concise, TypeScript can infer types without lots of hints, and the “damage scope” of null! is very limited.</p><h4>The empty array</h4><p>A last curious common occurrence of never that I’ll mention is this: TypeScript designates the type never[] to an empty array literal [].</p><p>That makes sense really, since an empty array has no element, so the type of that element is kind of moot.</p><p>But it may give you a surprise in the ad-hoc array flattening pattern. You can’t concat an array of never with anything!</p><pre>[].concat(...arrayOfArrays); // nope!</pre><p>Instead, you will need to give an element type to that initial array that matches what you’re spreading.</p><pre>new Array&lt;number&gt;().concat(...arrayOfArrays);</pre><p>(<a href="http://www.typescriptlang.org/play/index.html#code/CYUwxgNghgTiAEYD2A7AzgF3rGUCeA8gGYCCMueaAXPCgK4C2ARiDANoC6nA3AFC+cAdMhRgoGABSDpOfMTIU0ASn4oQAd3gL8AHnrNWAPglLhqMZOmDZhUuXzLuQA">playground link here</a>)</p><h3>The empty interface type {}</h3><p>There is a type that sometimes you will see. It has no primitive name, but it is expressible in this form: {} .</p><p>Don’t let that appearance of an empty object literal fool you, this type does <em>not</em> represent an object type. Instead, it represents a kind of “empty interface” type. Anything that is not null or undefined can be assigned to it.</p><pre>const a: {} = 2;<br>const b: {} = false;<br>const c: {} = {}<br>const d: {} = Symbol();<br>const e: {} = () =&gt; 42;<br>const f: {} = null; // nope<br>const g: {} = void 0; // nope</pre><p>Assigning a value of type {} to anything except for places expecting {}, unknown, and any will fail. You cannot access its property (except for properties that part of the Object prototype), and you cannot call it. Essentially, as an interface, it completely lacks in functionality.</p><p>When I first saw this behavior, I came to a conclusion that {} could be used as a non-null, non-undefined subtype of unknown — a kind of value which we have been casually referring to as a “concrete” value.</p><p>However, I ran into a problem.</p><p>If you use {} as a generic constraint with the intention of restricting nullish types, it will <em>not </em>be checked for when another generic applies a type to it. Check this example:</p><pre>interface WithConcreteProp&lt;T extends {}&gt;{<br>  concrete: T;<br>}<br>interface WithNullableProp&lt;T&gt; extends WithConcreteProp&lt;T&gt; { }</pre><pre>const foo: WithConcreteProp&lt;null&gt; = {<br>  concrete: null // nope<br>};</pre><pre>const bar: WithNullableProp&lt;null&gt; = {<br>  concrete: null // okay! ... wait... really?!<br>};</pre><p>(<a href="https://www.typescriptlang.org/play/?ts=3.6.3&amp;ssl=1&amp;ssc=1&amp;pln=15&amp;pc=2#code/JYOwLgpgTgZghgYwgAgOrDACwMIHsQJQSQAKUuADgDwAqyEAHpCACYDOyA3gL4B8nAKGTIE+QsQgAuZDQDcA7gNCRYiFOiwA5AK4AbXXABGuiGUq1e9JhFYcNOMUVLlqNS52SKBokGzDIYXFxpezwCJ1MXKhA9XUsAXi4hEUcJaRj9BXkfP2RDOCgQjEwdfSMTM2oMuOREwWEfcUh02KyBARhtAjBgfDy4AC8LAApA4LRisKbI8zcASi5kZLGAOkaIlYUgA">playground link here</a>)</p><p>Notice above how WithNullableProp is allowed to extend WithConcreteProp even if there isn’t the {} constraint. It <a href="https://github.com/microsoft/TypeScript/issues/36124#issuecomment-573145332">turned out</a> that in the generic context, the behavior around {}, default constraint and null is a bit inconsistent. The TypeScript team seems inclined to leave it alone, and I get it, since messing with null can take you into very dangerous places. As Hermione Granger said in <em>Harry Potter and The Prisoner of Azkaban</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YWgLdGEMLo-8EiEoi9Zsqg.jpeg" /><figcaption>With apologies to J.K. Rowling</figcaption></figure><p>So, you cannot use {} to represent “any concrete type” as generic constraint. Just be aware of that.</p><h3>Wrapping up</h3><ul><li>Use the unknown type when you are intentionally uncertain about the data type, and assert your way into the more appropriate type. This is safe.</li><li>Be aware that the any type turns off type checking. You’re on your own wherever you do this, but conversely any can help you gradually transition projects to TypeScript.</li><li>Use the undefined type to represent a<em> meaningful</em> undefined value, and the void type to represent the lack of a meaningful value — the difference between somebody saying “the answer is… nothing” and “I have nothing to say to you”.</li><li>Understand that you’re dealing with an impossible case when you come across never. You may wish to leverage it to add extra safety when you want to make sure that every possibility is accounted for.</li><li>The {} type may be thought as an unknown that excludes null and undefined. However, this is only my empirical observation, and it at least does <em>n</em>ot work this way as a generic constraint.</li></ul><p>TypeScript has applied many useful concepts that draw both from sound theoretical foundations like the top and bottom types, as well as from pragmatic motivation to improve developer experience. We have covered how meta types embody these concepts, and hopefully, you too will now be able to make good sense and good use of them.</p><p>Happy TypeScripting everyone!</p><p><em>Solution to the </em><em>async function riddle: An </em><em>async function always returns a </em><em>Promise even if it is doomed to throw an exception. See it </em><a href="https://www.typescriptlang.org/play/?ts=3.6.3#code/IYZwngdgxgBAZgV2gFwJYHsIwCbvQWwAoBKGAbwCgYYpMR0AbAUwDoH0BzQgIgEkYA7qgYMYTAB4AHdtibdiAbioxkACwBO6ATACi6zep64C8pQF8KtCPWZtOPUJFiIUGLOqbIE669wA0OHhExIqWdIys7Fx8AOT4MCBoIjDADKgAbkwA-ACEpkA"><em>here</em></a><em>. If you’re curious as to why this is so, “JavaScript event loop” is your Google search query. It’s another big topic of its own!</em></p><p>That said,<em> an </em><em>async function that runs into a </em>synchronous<em> infinite loop would of course not return. But any synchronous infinite loop would defy the very principle of JavaScript event loop to begin with. So TypeScript, in my opinion, does the sensible thing and discounts such an instance, instead insisting that all </em><em>async functions return a </em><em>Promise.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e17a8856b17" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/getting-to-know-and-love-typescripts-meta-types-5e17a8856b17">Getting to know and love TypeScript’s “meta” types</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A note on TypeScript non-null assertion operator]]></title>
            <link>https://medium.com/@tar.viturawong/a-note-on-typescript-non-null-assertion-operator-bad8fbe62bba?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad8fbe62bba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 10:31:41 GMT</pubDate>
            <atom:updated>2019-03-25T13:32:23.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMwiMJ8peWTDdgrY5ojE3Q.png" /><figcaption>Riddle: What is the type of the constant named “y”? (answer at the bottom)</figcaption></figure><p>Today, as I was browsing React’s typedoc on <a href="https://reactjs.org/docs/context.html">component context</a>, I came across something new about something that’s been in TypeScript for a while (way back in the brave new world of 2.0, in fact), namely the <a href="https://github.com/Microsoft/TypeScript/wiki/What&#39;s-new-in-TypeScript#non-null-assertion-operator">non-null assertion operator</a>.</p><pre>If using the new style context, re-declare this in your class to be theReact.ContextType of your static contextType.</pre><pre>* static contextType = MyContext<br>* context!: React.ContextType&lt;typeof MyContext&gt;<br>*</pre><pre><em>@deprecated</em> — if used without a type annotation, or without static contextType</pre><p>“context!”? … You scared me!</p><p>It turned out that this operator ! placed <em>after</em> an expression is TypeScript’s non-null assertion operator. It lets you deliberately ignore an expression’s possible null-ness on a case-by-case basis.</p><pre>let a: { foo: number }|null = null;<br>a.foo // ERROR: a is possibly null<br>a!.foo // OK, type number</pre><p>You can also use this operator to deliberately ignore void-ness, both owing to deliberate assignment and owing to the value not being reliably detected by TypeScript to have been assigned.</p><pre>let a: { foo: number };<br>new Promise(() =&gt; a = { foo : 1 });<br>a.foo <em>// ERROR: a is used before assigned (wrong*)<br></em>a!.foo <em>// OK</em></pre><p><em>*A </em><em>Promise callback is synchronously called on instantiating the promise, so </em><em>a is expected to be assigned. So this TypeScript error is nonsense. But it’s understandable that TypeScript cannot discriminate which expression is called immediately.</em></p><p>And this works just as well:</p><pre>let a: { foo: number } | undefined = void 0;<br>a.foo <em>// ERROR: a is possibly undefined<br></em>a!.foo <em>// OK</em></pre><h3>On class declaration</h3><p>As shown in the quoted typedoc on React’s context, you can also put! after a property declaration inside a class, and TypeScript will give up type-checking that property for not being initialized properly. For instance, with this <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">React callback ref</a> (inlined for brevity).</p><pre>class MyClass extends react.Component {<br>  private el!: HTMLInputElement;<br>  render(){<br>    return &lt;input ref={ el =&gt; this.el = el! }/&gt;<br>  }<br>  componentDidMount(){<br>    this.el.focus();<br>  }<br>}</pre><p>Without ! on the property declaration we will get a complaint that we never initialized el which is OK because we know that React will supply it with a proper value before we use it anyway. For part of the component’s lifecycle where it matters, el will always have a value, so we can also safely ignore the time where React assigns null to the ref by putting ! similarly in the ref callback.</p><h3>Splitting hair over nothing</h3><p>There are two subtle things to note:</p><ul><li>This operator will <strong>not</strong> ignore falsiness, so it will not ignore a union with false.</li><li>The operator curiously also does not work on a union with void. This seems to be another subtle difference between the void and undefined types.</li></ul><h3>Ignore responsibly</h3><p>The fine print of this operator is that it is <strong>completely your responsibility</strong> to take the risk of ignoring the nullness of your expression. In fact, TypeScript’s release note implicitly hints at a good practice:</p><pre>// Compiled with --strictNullChecks<br>function validateEntity(e?: Entity) {<br>    // Throw exception if e is null or invalid entity<br>}<br><br>function processEntity(e?: Entity) {<br>    validateEntity(e);<br>    let s = e!.name;  // Assert that e is non-null and access name<br>}</pre><p>That us to say, for the sake of your (and your fellow engineers’) sanity, you should probably throw a meaningful exception if it turns out that your assumption is wrong.</p><h3>When (not) to use it?</h3><p>TypeScript is wonderful in acknowledging that it sometimes cannot be as smart as we humans are in understanding the domain context in our specific applications. For this reason, there exist types such as any and unknown as well as the ability to globally ignore nullchecks by turning off strictNullChecks inside tsconfig.json. These features of TypeScript make it more humanly reasonable. This one-off nullcheck lift belongs to this throng of human overrides.</p><p>However, machines are generally better than humans when it comes to consistency. By overriding TypeScript’s safety checks you (and your peers — this is important!) assume the responsibility of maintaining the knowledge of how the shortcut can be seen as safe. Therefore, I would recommend that at least one of the following holds true when you use the operator:</p><ul><li>The usage context (e.g. according to knowledge about your code’s ecosystem that can reasonably be expected from all) obviously suggests that the use of the operator is safe. React callback refs of a static element is an example of such a case.</li><li>The operator use is immediately preceded by a check that would suggest that the usage is safe. The assertion used in TypeScript’s release notes is an example of such a case.</li><li>There is plenty of documentation why this is safe that is understandable by all. Often, if this is convoluted, it’s better to self-document with an explicit type assertion.</li></ul><p>Plus always this one point:</p><ul><li>It is absolutely clear where the scope of your knowledge/assumption about the safety of ignoring null begins and ends. Ideally, this is as small as possible in terms of code area. Do not allow the requirement for this knowledge to leak across natural code boundaries such as functions or classes (or even worse, files!).</li></ul><p>Do not use it just because you are lazy to think through why something is flagged as maybe null by TypeScript when it shouldn’t be. Ad-hoc overrides in this manner often merely hide a deeper flaw in reasoning that may be surfacing in other areas of your code.</p><h3>Alternatives</h3><p>In the same way that the a nation’s leader shouldn’t learn of the nuclear button until he or she fully understands the geopolitics and humanitarian challenges of their region, in a way I almost considered it a good fortune that I remained ignorant of this operator for so long.</p><p>While I have shown cases where the human override is the best way to reduce verbosity (like the Promise callback example), often there are ways to overcome the nuisance of redundant nullchecks without actually providing a manual override and all of its maintenance obligations. Let’s explore a couple of cases:</p><h4>I’m not null because something else is different</h4><p>You have a UI state that represents an AJAX request progress. It’s either in the initial state, pending state, complete state, or error state. Only in the complete state do you have the response, otherwise it is null.</p><p>While it is possible that you would make the response type nullable and just ignore the nullness once you have determined that you are in complete state, you might want to (if not constrained by e.g. third-party libraries) consider putting your UI state representation into a discriminated union. I covered discriminated unions at length in an article on <a href="https://medium.com/@tar.viturawong/using-typescripts-singleton-types-in-practice-f8b20b1ec3a6">singleton types</a>.</p><p>That is, instead of this:</p><pre>type AjaxState&lt;T&gt; = {<br>  state: &#39;initial&#39;|&#39;pending&#39;|&#39;complete&#39;|&#39;error&#39;;<br>  response: T|null;<br>}</pre><pre>// assume `ajaxState` is `AjaxState&lt;number[]&gt;`<br>if (ajaxState.state === &#39;complete&#39;){<br>  // &quot;complete&quot; state means response always exists<br>  console.log(ajaxState.response!.length);<br>} </pre><p>Communicate your human intention — that <em>“complete” state means response always exists</em> — to TypeScript.</p><pre>type AjaxState&lt;T&gt; = <br>  { state: &#39;initial&#39;|&#39;pending&#39;|&#39;error&#39;, response: null } |<br>  { state: &#39;complete&#39;, response: T };</pre><pre>// assume `ajaxState` is `AjaxState&lt;number[]&gt;`<br>if (ajaxState.state === &#39;complete&#39;){<br>  console.log(ajaxState.response.length);<br>}</pre><pre>console.log(ajaxState.response.length); <br>// above will give ERROR, value is possibly null</pre><p>Not only it is safe in assertion, it also makes sure that you cannot change your AjaxState state in ways that are inconsistent with the typing. Try it for yourself!</p><h4>I just know that it’s fine</h4><p>In <a href="https://medium.com/@tar.viturawong/the-true-power-of-typescript-generics-1303d78a1c9a">my last article</a> I introduced idea that you can use TypeScript generics to create your own arbitrary type logic. In that piece, I mentioned this function:</p><pre>function requireValue&lt;ValueType&gt;(input: MaybeNull&lt;ValueType&gt;){<br>  if (input === null) throw Error(&quot;value is required!&quot;);<br>  return input;<br>}</pre><p>Where MaybeNull&lt;T&gt; = T|null</p><p>This essentially provides a typesafe alternative to the ! operator and a way for you to throw a meaningful, semantic error (just pass your own favourite message instead), and you could use it like this:</p><pre>// iKnowThisIsntNull is technically null|{ doSomething: () =&gt; void }<br>requireValue(iKnowThisIsntNull).doSomething();</pre><p>You could even safe the result into a new variable, from which point it is null-free.</p><h3>Conclusion</h3><p>The postfix ! operator can provide a quick way to ignore the null part of an expression. As with other TypeScript mechanisms that allow human overrides like any and the as operator, usage comes with a cost of knowledge maintenance. In this article I have outlined the healthy way of using this operator that could also extend to other human overrides.</p><p>Now go and enjoy that healthy human-machine relationship, and celebrate our appreciation of each other ❤<em>️.</em></p><p><em>*Answer to the riddle at the top: The type of </em><em>y as shown in the expressions in the image is the TypeScript type known as </em><em>never. Because</em><em>x is a constant, its type is the same as its value literal’s type:</em><em>null . The expression for constant </em><em>y — </em><em>x! — is saying “take the value of </em><em>x and ignore the case where it is null”. But since </em><em>x is always null, being a constant, we have an impossible scenario in </em><em>y .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad8fbe62bba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The true power of TypeScript generics]]></title>
            <link>https://medium.com/@tar.viturawong/the-true-power-of-typescript-generics-1303d78a1c9a?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/1303d78a1c9a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 16:50:13 GMT</pubDate>
            <atom:updated>2019-03-10T15:31:05.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S_wAgfM3VVlRq6Uw" /><figcaption>Generics: “This is not even my final form!” Photo credit: <a href="https://unsplash.com/@alisaanton?utm_source=medium&amp;utm_medium=referral">Alisa Anton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I promised at the end of my last <a href="https://medium.com/@tar.viturawong/using-typescripts-singleton-types-in-practice-f8b20b1ec3a6">TypeScript article on singleton types</a> to share more thoughts about TypeScript’s true power. As I said then, TypeScript is often (wrongly) assume to be stripped of the kind of expressive flexibility that JavaScript — with the kind of “anything goes” approach to typing — affords. In this article, we shall pick another awesome aspect of TypeScript to debunk this myth. And what other aspect is better suited to debunk the <em>inflexibility</em> myth than the topic of <em>generics</em>?</p><p>Let’s go.</p><h3>Generics as generalization</h3><blockquote>“You spend your entire life studying a bucket. Once you understand the one bucket fully, the others are all the same.”</blockquote><blockquote>— <a href="https://en.wikipedia.org/wiki/Ajahn_Chah">Ajahn Chah</a> <em>on understanding the mind.</em></blockquote><p><strong><em>If you have programmed in other languages that feature the concept of templates and generics in some form, this section may not be interesting to you. :)</em></strong></p><p>Living in Europe for so long, one of the observations I like is that when spring approaches, people would start putting on summer wear when the temperature reaches about 10 degrees celcius. (Having come from Thailand, I think that’s crazy, but that’s beside the point.) Curiously, as winter looms, we start wrapping up in our winter wear way before it falls to 10 degrees. It’s often not the absolute situation in life but rather its <em>change</em> that motivates us to do things.</p><p>Now that I’m done indulging in a soliloquy, let’s use the little story above in demonstrating how generics work in TypeScript. We could model the changes in temperature and changes in clothing in TypeScript-land like this:</p><pre>interface ChangeInTemperature {<br>  oldValue: number;<br>  newValue: number;<br>}</pre><pre>interface ChangeInClothing {<br>  wasWearingWinterClothes: boolean;<br>  isWearingWinterClothes: boolean;<br>}</pre><p>Suppose we have to inspect this change-in-temperature object to see if there really is a change, we could write a function like so:</p><pre>function hasTemperatureChanged(change: ChangeInTemperature){<br>  return change.oldValue !== change.newValue; // inferred boolean<br>}</pre><p>We can just as well inspect the change in clothing to the same intention; that is, see if there is a change:</p><pre>function hasClothingChanged(change: ChangeInClothing){<br>  return change.wasWearingWinterClothes !== <br>    change.isWearingWinterClothes;<br>}</pre><p>Now, both of these functions are essentially doing the same thing: they inspect an object with property semantics of something that represents an older value, and something that represents a newer value. The only differences are that:</p><ul><li>The properties were <em>named </em>differently to be semantically precise.</li><li>The properties were of different <em>types </em>because of the nature of information they carry.</li></ul><p>Now, let’s suppose further that we also want to represent what we think about the weather (“gorgeous”, “pleasant”, “meh”, “awful”) and how that has changed. We would also need a similar kind of declaration to cover the functionality we have given to the other two “change” objects:</p><pre>type WeatherOpinion = &quot;gorgeous&quot;|&quot;pleasant&quot;|&quot;meh&quot;|&quot;awful&quot;;</pre><pre>interface ChangeInWeatherOpinion {<br>  oldOpinion: WeatherOpinion;<br>  newOpinion: WeatherOpinion<br>};</pre><pre>function hasWeatherOpinionChanged(change: ChangeInWeatherOpinion){<br>  return change.oldOpinion !== change.newOpinion;<br>}</pre><p>Another interface, another type, but still exactly the same concept.</p><p>This is the kind of situation where TypeScript generics may help you. We can define a <em>generic interface</em> that represents a change in value. We don’t really know what type that value will take, but we know that the old value and the new value will share the same type:</p><pre>interface ChangeRecord&lt;ValueType&gt; {<br>  oldValue: ValueType;<br>  newValue: ValueType;<br>}</pre><p>We will refer to the yet-unknown value type which should be the same between the old and new values as ValueType . The name could be anything, as long as it is consistent within the &lt;&gt; and where it’s being used. Our ValueType is a type name that only makes sense within the definition of the interface, and it is called a <em>generic type parameter</em>.</p><p>So how do we use this interface to describe temperature changes, clothing changes, and weather opinion changes?</p><p>Since temperature is a number,a change in temperature is a change in numeric value. Therefore, we could express ChangeInTemperature as ChangeRecord&lt;number&gt;.</p><pre>type ChangeInTemperature = ChangeRecord&lt;number&gt;;</pre><p>Here, we are telling TypeScript to define ChangeInTemperature as a <em>specialization </em>of the generic interface ChangeRecord. Wherever we had put the generic type parameter ValueType inside the declaration of ChangeRecord, we should now replace it with number. In this place, number is a <em>generic type argument</em>. The resulting type for ChangeInTemperature is therefore:</p><pre>type ChangeInTemperature = {<br>  oldValue: number; // ValueType becomes number<br>  newValue: number; // ValueType becomes number<br>};</pre><p>We could now do the same for our clothing and weather opinion changes. Because we’re thinking generically we have to accept that we’re going use the same properties to represent the notion of “old” and “new” respectively. So to make oldValue and newValue meaningful in all cases, we’ll rename our types slightly:</p><pre>// true means &quot;wearing winter clothes&quot;, false otherwise<br>type ChangeInWinterWear = ChangeRecord&lt;boolean&gt;;</pre><pre>type ChangeInWeatherOpinion = ChangeRecord&lt;WeatherOpinion&gt;;</pre><p>What about our three functions that check whether a change actually exists? That, too, can be generalized into a single <em>generic function</em>:</p><pre>function isChanged&lt;ValueType&gt;(change: ChangeRecord&lt;ValueType&gt;){<br>  return change.oldValue !== change.newValue;<br>}</pre><h4>Adding constraints to generics</h4><p>In our isChanged function above, we are performing a strict equality === check on the old and new values. This only makes sense for primitives. But our generic so far will let through absolutely everything as long as the old and new values are of the same type, resulting in a use case that may be unintended.</p><p>To stop this, we can add an extends clause to say what kind of type is allowed to be provided as generic type argument to ChangeRecord.</p><pre>interface ChangeRecord&lt;ValueType extends string|number|boolean&gt; {<br>  /* ... */<br>}</pre><p>Now an attempt to create a type ChangeRecord&lt;object&gt; will fail.</p><h4>Debugging generic type-check</h4><p>Let’s test out our shiny generic types.</p><pre>const test1: ChangeInWinterWear = { <br>  oldValue: false, <br>  newValue: true<br>};<br>isChanged(test1); // type OK</pre><pre>const test2: ChangeInWeatherOpinion = {<br>  oldValue: &quot;gorgeous&quot;,<br>  newValue: &quot;meh&quot;<br>};<br>isChanged(test2); // type OK</pre><pre><br>interface NotAChangeRecord {<br>  oldValue: number;<br>  newValue: string;<br>}<br>const test3: NotAChangeRecord = {<br>  oldValue: 42,<br>  newValue: &quot;blah&quot;<br>};<br>isChanged(test3); // type ERROR</pre><p>If you go over to the <a href="https://www.typescriptlang.org/play/#src=interface%20ChangeRecord%3CValueType%3E%20%7B%0D%0A%20%20oldValue%3A%20ValueType%3B%0D%0A%20%20newValue%3A%20ValueType%3B%0D%0A%7D%0D%0A%0D%0Atype%20WeatherOpinion%20%3D%20%22gorgeous%22%20%7C%20%22pleasant%22%20%7C%20%22meh%22%20%7C%20%22awful%22%3B%0D%0A%0D%0Atype%20ChangeInTemperature%20%3D%20ChangeRecord%3Cnumber%3E%3B%0D%0Atype%20ChangeInWinterWear%20%3D%20ChangeRecord%3Cboolean%3E%3B%0D%0Atype%20ChangeInWeatherOpinion%20%3D%20ChangeRecord%3CWeatherOpinion%3E%3B%0D%0A%0D%0Afunction%20isChanged%3CValueType%3E(change%3A%20ChangeRecord%3CValueType%3E)%7B%0D%0A%20%20return%20change.oldValue%20!%3D%3D%20change.newValue%3B%0D%0A%7D%0D%0A%0D%0Aconst%20test1%3A%20ChangeInWinterWear%20%3D%20%7B%20%0D%0A%20%20oldValue%3A%20false%2C%20%0D%0A%20%20newValue%3A%20true%0D%0A%7D%3B%0D%0AisChanged(test1)%3B%20%2F%2F%20type%20OK%0D%0A%0D%0Aconst%20test2%3A%20ChangeInWeatherOpinion%20%3D%20%7B%0D%0A%20%20oldValue%3A%20%22gorgeous%22%2C%0D%0A%20%20newValue%3A%20%22meh%22%0D%0A%7D%3B%0D%0AisChanged(test2)%3B%20%2F%2F%20type%20OK%0D%0A%0D%0Ainterface%20NotAChangeRecord%20%7B%0D%0A%20%20oldValue%3A%20number%3B%0D%0A%20%20newValue%3A%20string%3B%0D%0A%7D%0D%0Aconst%20test3%3A%20NotAChangeRecord%20%3D%20%7B%0D%0A%20%20oldValue%3A%2042%2C%0D%0A%20%20newValue%3A%20%22blah%22%0D%0A%7D%3B%0D%0AisChanged(test3)%3B%20%2F%2F%20type%20ERROR">TypeScript playground</a> with the code above and hover on each use of isChanged, you will see that TypeScript has inferred the type of argument for us.</p><p>In the final instance, the oldValue and newValue are not of the same type. Since they are not of the same type, they cannot possibly represent a ChangeRecord type regardless of what ValueType we would give it. Therefore, TypeScript gives us this error:</p><pre>Argument of type &#39;NotAChangeRecord&#39; is not assignable to parameter of type &#39;ChangeRecord&lt;number&gt;&#39;.<br>  Types of property &#39;newValue&#39; are incompatible.<br>    Type &#39;string&#39; is not assignable to type &#39;number&#39;.</pre><p>Niceness. Generic type-check: check!</p><p>But before we celebrate, let’s just look at that error message again.</p><pre>Argument of type &#39;NotAChangeRecord&#39; is not assignable to parameter of type &#39;ChangeRecord&lt;number&gt;&#39;.<br>  Types of property &#39;newValue&#39; are incompatible.<br>    Type &#39;string&#39; is not assignable to type &#39;number&#39;.</pre><p>The compiler clearly had to try to fit the NotAChangeRecord type into ChangeRecord&lt;number&gt; and ChangeRecord&lt;string&gt; , since they were the closest possibilities. Of course, neither fitted because our object had a string as one property and a number as the other. That there is an error clearly makes sense.</p><p>However, behold here what I consider a developer experience fail. What the compiler did then was to blurt out— quite arbitrarily, mind you— just the one attempt at matching ChangeRecord&lt;number&gt;. In this case, both the string and number specialization are just “as mismatched” as the other. I have seen cases where I make a mistake while trying to match specialization A, and TypeScript blurts out errors from trying to match specialization B, which is unfortunately not helpful.</p><p>It’s as if <a href="https://youtu.be/GI5kwSap9Ug?t=115">you’re trying to go to some bureaucratic department to ask for a particular form and the way you phrase your technical words make the clerk think you’re trying to register a ship, from which point on the conversation is all about going to the port</a>. TypeScript, as brilliant as it is, behaves a bit like that clerk sometimes.</p><p>The bottom line here is:</p><blockquote>If you run into a generic type-check error, don’t take TypeScript’s message too literally. Remember what *your* own intentions are.</blockquote><h4>Read more on generics</h4><p>Lots have been written about how to use generics in practice out there. If you’re completely new to the idea, or to TypeScript, or both, the <a href="https://www.typescriptlang.org/docs/handbook/generics.html">TypeScript handbook</a> is a great place to start.</p><p>I really want to move on to what makes generics in TypeScript so awesome, namely…</p><h3>Generics as type meta-programming</h3><p>In TypeScript, generics can do so much more than specializing classes, interfaces or functions, thanks to the <strong>various syntactic constructs operating at type level which let you create new types programmatically</strong>. Remember that TypeScript doesn’t emit any JavaScript that has anything to do with type declarations (with <a href="https://www.typescriptlang.org/docs/handbook/enums.html">enums</a> being the only exception for technical reasons) so the expressions I will show you will add type dynamicity and strictness without any burden on your JavaScript output.</p><p>In this part, I will show you a family of “maybe” types that you might find useful, which will demonstrate the TypeScript’s ability to meta-program types in your code.</p><p><strong>Generic unions</strong></p><p>In <a href="https://medium.com/@tar.viturawong/using-typescripts-singleton-types-in-practice-f8b20b1ec3a6">my previous article</a> I have used the <em>union operator</em>. Let’s revisit what this means:</p><pre>type NumberOrString = string|number;</pre><p>Simple as that. A numeric value or a string value matches type NumberOrString. The type operator | is the <em>union</em> operator and it means that the type on either side counts as a match.</p><pre>const test1: NumberOrString = 42; // OK<br>const test2: NumberOrString = &quot;hello&quot;; // OK<br>const test3: NumberOrString = false; // Type Error</pre><p>So we could also define a type of “something or null”. Let’s suppose, string-or-null:</p><pre>type StringOrNull = string|null;<br>const test1: StringOrNull = &quot;hello&quot;; // OK<br>const test2: StringOrNull = null; // OK<br>const test3: StringOrNull = 42; // Type Error</pre><p>Of course, other variants of “something or null” would make sense too:</p><pre>type NumberOrNull = number|null;<br>type BooleanOrNull = boolean|null;</pre><p>That’s right, we’re also looking at a generic here! To express a type that represent “something or null”, we could do this:</p><pre>type MaybeNull&lt;ValueType&gt; = ValueType|null;<br>const test1: MaybeNull&lt;string&gt; = &quot;hello&quot;; // OK<br>const test2: MaybeNull&lt;number&gt; = null; // OK<br>const test3: MaybeNull&lt;boolean&gt; = 42; // Type Error</pre><p>Now, that’s nice. But it gets even nicer when we then leverage TypeScript’s well-intended attempt to resolve types from existing information as far as possible. Look at this function:</p><pre>function requireValue&lt;ValueType&gt;(input: MaybeNull&lt;ValueType&gt;){<br>  if (input === null) throw Error(&quot;value is required!&quot;);<br>  return input;<br>}</pre><p>One could use this function as a dare-devil way of saying “<em>I know this value could </em>technically <em>— per type declaration — be null, but I also know that </em>in this particular instance<em> it could never be. So shut up and give me my non-null value and let me pay for my own assumption should it ever prove incorrect</em>.” Because null has been thrown away, this function returns just the non-null part of your argument. Therefore, TypeScript will generically mark the result of this function as ValueType.</p><pre>// suppose &quot;test1&quot; is of type MaybeNull&lt;string&gt;<br>requireValue(test1); // string</pre><pre>// suppose &quot;test2&quot; is of type MaybeNull&lt;number&gt;<br>requireValue(test2); // number</pre><p>The reason why TypeScript can “de-unionize” the input argument and gives us just the non-null portion is thanks to the generics.</p><p>“But I can do this in other languages with nullable support too!”, you said. Yes indeed, so let’s look at something else.</p><h4>Call me maybe?</h4><p>If you have done any amount of production JavaScript, you will have come across a configuration hell where some setting takes a string, a regex, an object, or a function, and it all does something different in very subtle ways. (If you use Webpack, <a href="https://twitter.com/jaffathecake/status/878160747909365761?lang=en">this is still my favourite meme</a>.)</p><p>That said, there is still merit in polymorphic configuration. Let’s consider a problem in this direction: suppose you want to allow a configuration that either takes a number or function of certain arguments that returns a number. That is to say, for instance:</p><pre>{<br>   happinessScoreToday: 10<br>}</pre><p>or</p><pre>{<br>  happinessScoreToday: weatherOpinion =&gt; <br>    weatherOpinion === &quot;gorgeous&quot; ? 10 : 5<br>}</pre><p>What is the type of happinessScoreToday ?</p><p>As a one off, we could say that it’s either a number, or a function that returns a number. That is to say:</p><pre>type HappinessScoreConfig = <br>  | number <br>  | (weatherOpinion: WeatherOpinion) =&gt; number;</pre><p>That’s one configuration. Suppose all your configurations take a similar constant-or-function form. We can generalize this kind of union into a MaybeConstant generic type, which we will now define:</p><pre>type MaybeConstant&lt;Function extends (...args: any[]) =&gt; any&gt; =<br>  Function|ReturnType&lt;Function&gt;;</pre><p>This generic defines a type that is either the function type provided as generic type argument, or its return type as a constant. The magic built-in type ReturnType is itself a generic — we will revisit this soon — that extracts the return value of the function type argument.</p><p>With this, we can rewrite our happiness score config type as follows:</p><pre>type HappinessScoreConfig = <br>  MaybeConstant&lt;(weatherOpinion: WeatherOpinion) =&gt; number&gt;;</pre><p>That’s not much shorter, but it’s semantically very clear what we’re trying to do here. Also note that TypeScript will discriminate the alternations just fine when you actually try to use the type:</p><pre>function useConfig(config: HappinessScoreConfig): number {<br>  // return config; // can&#39;t do this, might be function!<br>  // return config(&quot;gorgeous&quot;); // can&#39;t do this, might be number!<br>  if (typeof config === &quot;number&quot;) return config; // OK<br>  return config(&quot;gorgeous&quot;); // also OK, can only be function.<br>}</pre><h4>Promise me… maybe?</h4><p>You have a function that may complete synchronously or asynchronously but must eventually return a value of a certain type?</p><pre>type MaybePromise&lt;ValueType&gt; = ValueType|Promise&lt;ValueType&gt;;</pre><p>You could even combine it with the MaybeConstant we already defined earlier:</p><pre>type ResolveHappinessConfig = <br>  MaybeConstant&lt;(weatherOpinion: WeatherOpinion) =&gt; <br>    MaybePromise&lt;number&gt;&gt;;</pre><p>The type ResolveHappinessConfig accepts a number, a function accepting a WeatherOpinion that returns a number, a Promise that resolves to number, or a function that returns a Promise that resolves to number. Woooo!</p><h4>Give me a lot… maybe?</h4><p>Your API can accept a single query or multiple queries? No problem:</p><pre>type MaybeArray&lt;ValueType&gt; = ValueType|ValueType[];</pre><h4>Undoing generic unions</h4><p>We have defined a few “maybe” types that are generic unions: MaybeArray, MaybePromise, MaybeConstant and MaybeNull. We have also shown how to generically extract the non-null type from the MaybeNull type and extract the constant type from the MaybeConstant using the “magic” ReturnType.</p><p>Using similar techniques, can you correctly type these functions?</p><ul><li>a function that would take a MaybeArray argument and return either the only item (if it’s not an array) or the first item (if it is an array)?</li><li>a function that would take a MaybePromise argument and always resolve asynchronously to the resolved value (if wrapped in a promise) or the input value (if not a promise)?</li></ul><h4>Infer</h4><p>I said earlier that I would explain the ReturnType generic and how it is able to extract the return argument from a function type.</p><p>Let’s look at the definition of ReturnType type, which is built in with TypeScript.</p><pre>type ReturnType&lt;T&gt; = T extends (...args: any[]) =&gt; infer R ? R : any;</pre><p>“infer?! what are you letting me in<em>fer</em> now?” (If you didn’t get that, I’m sorry. If you did get that, … I’m sorry.)</p><p>We are seeing two constructs that play closely together. First, the “extend-tenery-operator-looking-thing” takes this form:</p><pre>type X = A extends B ? C : D;</pre><p>This means, type X is the same as type C if type A extends type B . Otherwise, type X is the same as type D. This construct A extends B ? C : Dis known as the <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html"><em>conditional type expression</em></a>, and it features the conditional type operator ... extends ... ? ... : ..., which is conceptually not unlike the ternery operator we know and love in JavaScript.</p><p>Next, we see the keyword infer. Note that this keyword appears in front of the type R, which we did not so far declare anywhere.</p><p>Look at our conditional type A extends B ? C : D again, the main part of the condition — the predicate if you will — is type B, because it determines whether the whole type expression will resolve to one branch or another. In this B position, we can have a complex type expression involving many types, such as (...args: any[]) =&gt; any . Instead of hard-coding a type in this expression, what we can do instead is to substitute a type with infer &lt;Identifier&gt; , such as (...args: any[]) =&gt; infer R . TypeScript will then attempt to match the input type (here A) to this type the best it can. Once matched, the type that match the infer position will be “captured” into that identifier.</p><p>infer can be scary to read at first, so let’s get practical and look at ReturnType definition again:</p><pre>type ReturnType&lt;T&gt; = <br>  T extends (...args: any[]) =&gt; infer R ? R : any;</pre><p>It’s saying:</p><ul><li>The return type of T is…</li><li>Well, is T a function? While you’re trying to match it to a function, find out what the return type is (T extends (...args: any[]) =&gt; infer R)</li><li>If T is a function, then the type resolves to the inferred return type R .</li><li>Otherwise the type resolves to any.</li></ul><p>To better understand how infer works, let’s practice it on our various Maybe* types. How can we create a type that converts a type to the element of an MaybeArray if</p><pre>type MaybeArrayItem&lt;T&gt; = ... ? </pre><p>Did you get something like this?</p><pre>type MaybeArrayItem&lt;T&gt; = <br>   T extends Array&lt;infer Element&gt; ? Element : T;</pre><p>That is to say, if my type is an array, extract the element, otherwise the input type is exactly the result?</p><p>Try generically “undoing” the types MaybePromise, MaybeConstant and MaybeNull into the “important parts” (the resolved value, the return value, and the non-null value) using infer. (Answers <a href="https://www.typescriptlang.org/play/#src=type%20MaybeArray%3CValueType%3E%20%3D%20ValueType%20%7C%20ValueType%5B%5D%3B%0D%0Atype%20MaybeNull%3CValueType%3E%20%3D%20ValueType%20%7C%20null%3B%0D%0Atype%20MaybeConstant%3CFn%20extends%20(...args%3A%20any%5B%5D)%20%3D%3E%20any%3E%20%3D%20ReturnType%3CFn%3E%20%7C%20Fn%3B%0D%0Atype%20MaybePromise%3CValueType%3E%20%3D%20ValueType%20%7C%20Promise%3CValueType%3E%3B%0D%0A%0D%0Atype%20MaybeArrayItem%3CT%3E%20%3D%20T%20extends%20Array%3Cinfer%20Element%3E%20%3F%20Element%20%3A%20T%3B%0D%0Atype%20DeNull%3CT%3E%20%3D%20T%20extends%20infer%20NonNull%20%7C%20null%20%3F%20NonNull%20%3A%20T%3B%0D%0Atype%20MaybeConstantValue%3CT%3E%20%3D%20T%20extends%20(...args%3A%20any%5B%5D)%20%3D%3E%20infer%20Return%20%3F%20Return%20%3A%20T%3B%0D%0Atype%20MaybePromiseResolve%3CT%3E%20%3D%20T%20extends%20Promise%3Cinfer%20Resolve%3E%20%3F%20Resolve%20%3A%20T%3B">here</a>)</p><h3>Wrapping up</h3><p>Conditional type expressions and infer operator together form part of the basic building blocks allowing TypeScript to express a seemingly arbitrarily complex type logic. It is this ability that allows TypeScript to support the dynamic nature of your codebase’s types that, for me, truly sets TypeScript aside from the sterotype of inflexibility derived from typed languages. For me, this also frees TypeScript from the general criticism against bringing typing into JavaScript on grounds of incompatibility with the latter’s existing idioms.</p><p>There is still much more that generic type expressions can do. Later, in a different article, I will show more TypeScript metaprogramming, what it can be used for beyond the obvious, and some of the developer experience observations surrounding it. Till then!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1303d78a1c9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using TypeScript’s singleton types in practice]]></title>
            <link>https://medium.com/@tar.viturawong/using-typescripts-singleton-types-in-practice-f8b20b1ec3a6?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8b20b1ec3a6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Sat, 29 Sep 2018 17:55:20 GMT</pubDate>
            <atom:updated>2020-02-27T02:57:01.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QdFlVEAV6edyGySs" /><figcaption>Some rocks are special. So are some primitive literals. Photo credit: <a href="https://unsplash.com/@arstyy?utm_source=medium&amp;utm_medium=referral">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To many of us who delight in JavaScript’s flexibility, TypeScript may appear at first like “a step backwards” to some forced object-oriented patterns and maintaining a ganglion of type declarations. However, such perception is hardly an accurate depiction of TypeScript, whose developers have made appreciable effort to embrace the living idioms of JavaScript, while letting TypeScript do the hard work on its own to a great degree.</p><p>One such effort is portrayed in a TypeScript feature known as “singleton types”. I will first show we can use TypeScript’s singleton types to make JavaScript code safer and more traceable, from a theoretical perspective. In the second part, I will relate some of my practical experience in putting singleton types into good use in more complex situations.</p><h3>Part one: The promises of singleton types</h3><p>Singleton typing — also known as “literal typing” — is when TypeScript sees a specific primitive value as exactly that value, rather than a value of that primitive’s type. For instance, the value &quot;Medium&quot; can be seen as type string, but it can also be seen as type &quot;Medium&quot; i.e. exactly that string value, which is a subset of type string (along with &quot;cat&quot;, &quot;dog&quot; , &quot;broccoli&quot; , and everything else)</p><p>When you declare numeric or string constants using literals, they will have singleton types.</p><pre>const x = &quot;cat&quot;;   // Type: &quot;cat&quot;<br>const y = 20;      // Type: 20</pre><p>Likewise, when you return a string or numeric literals, they too will have singleton types.</p><pre>// Return Type: &quot;ComeDancing&quot;<br>function strictlyComeDancing() {<br>  return &quot;ComeDancing&quot;;<br>}</pre><p>You can also define a singleton type explicitly</p><pre>type ExactlyCat = &quot;cat&quot;;<br>type ExactlyTwenty = 20;</pre><p>You can also bundle a set of semantically related literal types in “enums”:</p><pre>enum PetKind {<br>  cat      = &quot;cat&quot;,<br>  dog      = &quot;dog&quot;,<br>  hedgehog = &quot;hedgehog&quot;<br>}<br>const myPet = PetKind.cat;<br>myPet === &quot;cat&quot;;       // true<br>myPet === PetKind.cat; // true<br>myPet === &quot;dog&quot;;       // Type Error</pre><p>An extra niceness about enums is that they have 100% semantic distinction. Even if you have two enums with same values, they cannot be compared.</p><pre>enum PetKind {<br>  cat      = &quot;cat&quot;,<br>  dog      = &quot;dog&quot;,<br>  hedgehog = &quot;hedgehog&quot;<br>}</pre><pre>enum ConservationAnimalKind {<br>  hedgehog = &quot;hedgehog&quot;,<br>  elephant = &quot;elephant&quot;<br>}</pre><pre>PetKind.hedgehog === ConservationAnimalKind.hedgehog // ERROR</pre><p><em>“OK, nice. But how is this useful?”</em></p><p>Singleton types don’t do much on their own, but they play an important part in some quite powerful typing techniques. We’ll explore them now.</p><h4>Maintaining conditional expression integrity</h4><p>Suppose we have a function that validates — superficially for the sake of illustration — an input field that should be a valid email address, and we want more than information that whether the email is valid or not (i.e. why it might be invalid):</p><pre>function validateRequiredEmail(value: string)<br>{<br>    if ( !value ) return &quot;empty&quot;;<br>    if ( value.indexOf(&#39;@&#39;) &lt; 0 ) return &quot;noAtSign&quot;;<br>    return null;<br>}</pre><p>The return type of validateRequiredEmail is a <em>union</em> of null (for no error) and two singleton types indicating error, namely: &quot;empty&quot; and &quot;noAtSign&quot;. TypeScript infers this from the function body, so we don’t have to annotate the return type.</p><p>When you actually call this function, TypeScript will make sure you are making only sensible assertions over the return result.</p><pre>const validationResult = validateRequiredEmail(&quot;not an email&quot;);<br>if ( validationResult === &quot;empty&quot; ) doThis();<br>else if ( validationResult === &quot;noAtSign&quot; ) doThat();<br>else if ( validationResult === &quot;broccoli&quot; ) doSomethingElse();</pre><p>The last else if statement will fail because validationResult , although it can be a string, can <em>never</em> return &quot;broccoli&quot;. In reality, if you assert against &quot;broccoli&quot; , you probably expect it to be one of the outcomes, and here it isn’t, so something is probably wrong. TypeScript is flagging code integrity issues to you. You would not get this shout-out if validateRequiredEmail returned just a string type.</p><h4>Discriminated unions</h4><p>We have seen how a union of singleton types help writing safer conditional statements. The idea above can then be extended in pattern called <em>discriminated</em> <em>union</em>.</p><p>If each type making up a union shares a common singleton-typed property, we can “discriminate the union” — choose to narrow on a specific one — by disambiguating this singleton-typed property.</p><p>To demonstrate this, let’s look at the code below:</p><pre>interface Cat<br>{<br>  kind: &quot;cat&quot;; <br>  name: string;<br>  isRescued: boolean;<br>  likesFurball: boolean;<br>  isAfraidOfDogs: boolean;<br>  chasesBirds: boolean;<br>}</pre><pre>interface Dog<br>{<br>  kind: &quot;dog&quot;;<br>  name: string;<br>  likesMilkbones: boolean;<br>  chasesCats: boolean;<br>}</pre><pre>interface Hedgehog<br>{<br>  kind: &quot;hedgehog&quot;;<br>  name: string;<br>  variant: &quot;african&quot;|&quot;european&quot;;<br>}</pre><pre>type Pet = Cat|Dog|Hedgehog;</pre><p><em>Disclaimer: </em><a href="https://en.wikipedia.org/wiki/Domesticated_hedgehog#Legality"><em>hedgehogs are only legal as pets in some areas of the world</em></a><em>!</em></p><p>Now suppose we have a variable pet of type Pet. Let’s try to do a few things with it:</p><pre>console.log(pet.name);    // OK<br>console.log(pet.variant); // ERROR</pre><p>Without any if condition, it’s not possible to access pet.variant , which is only specific to Hedgehog. To access the variant, you need to assert that your pet is a hedgehog before:</p><pre>if (pet.kind === &quot;hedgehog&quot;) {<br>  console.log(pet.variant);     // OK<br>  console.log(pet.chasesBirds); // ERROR<br>}</pre><p>The if block acts as a <em>type guard </em>for Hedgehog by asserting the discriminant property of the discriminated union, namely the kind property. Inside the if block, pet is now a Hedgehog and <em>only</em> a Hedgehog : TypeScript will not let us ask if our hedgehogs can chase birds.</p><h4>Discriminating overloads</h4><p>Another TypeScript feature benefiting from singleton types is the ability to annotate a function’s multiple overloads, so that it can be called with different combination of arguments. Perhaps the most well known example is the addEventListener method, which accepts a different kind of event handler depending on which event you’re attaching.</p><pre>myElement.addEventListener(&#39;keypress&#39;, ev =&gt; { /* ... */ } );<br>myElement.addEventListener(&#39;mousemove&#39;, ev =&gt; { /* ... */ } );</pre><p>When you call addEventListener with &quot;keypress&quot;, the ev object will have the <a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent">key property</a> that gives you the key code of the key that was pressed. This property will not be available in ev of the callback for&quot;mousemove&quot;, which would instead have <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent">mouse coordinate properties</a> like clientX.</p><p>This kind of overload is pretty idiomatic of living JavaScript, and typing such overloads exactly would not be possible without singleton types.</p><h4>Exact indexing</h4><p>Take the example from our validateRequiredEmail function’s return type again. Suppose that we want to then map our error codes to some user-facing text, we could use a series of if / else clauses as we have shown above.</p><p>However, this is not very re-usable as a pattern, and does not scale very nicely if there are more possible outcomes. What we could do instead is just use our return value as an <em>index</em> to an object that provides those keys.</p><pre>const errorMessages = {<br>  empty: &quot;This field is required.&quot;,<br>  noAtSign: &quot;This does not look like a valid email.&quot;<br>};</pre><pre>const validationResult = validateRequiredEmail(&quot;not an email&quot;);<br>if (validationResult) {<br>  console.log(errorMessages[validationResult]);<br>}</pre><p>Since we guard validationResult for truthiness, the null value falls away, leaving only &quot;empty&quot;|&quot;noAtSign&quot; as its type. This type is perfectly good to index the object errorMessages, whose properties are also exactly empty and noAtSign.</p><p>At this point, if you delete a property from errorMessages, TypeScript will complain that validationResult can no longer be used to index the object. If you let validationResult return another value (like &quot;broccoli&quot;), TypeScript will complain in the same way… until you add broccoli as a property to errorMessages too. Here also, the singleton types have better safety and traceability than string types.</p><h3>Part two: The practical gotchas</h3><blockquote>“To know a thing well, know its limits; Only when pushed beyond its tolerance will its true nature be seen.”</blockquote><blockquote>― Frank Herbert, Children of Dune.</blockquote><p>Hopefully I have made a convincing pitch for why singleton types are awesome in principle. Now I will switch role to play the sharks’ advocate, and show you some obstacles you might face.</p><p>One of the reasons why I love TypeScript is its intention to give you a lot of code integrity check with minimal efforts. I’m talking about the fact that one should be able to minimally add types where needed, and TypeScript will infer the rest. We have seen a couple of examples of this in the first part.</p><p>To do this, TypeScript needs to make some assumptions on our behalf. Unfortunately, this is also where leaving things fully to TypeScript can make things break, sometimes for seemingly incomprehensible reasons. There are a couple of subtle things that I want to share.</p><h4>When TypeScript sees a singleton type</h4><p>Having marveled at how discriminated unions can help giving sense to my data structures, I wanted to create a function that wraps <a href="https://github.com/axios/axios">Axios</a> in making a specific HTTP request, and returns a union of outcomes that are relevant to my application’s semantics. I innocently charged ahead and created this function below.</p><pre>import { default as axios, AxiosError } from &quot;axios&quot;;<br>async function login(username: string, password: string) {<br>  try {<br>    const response = await axios.post(&quot;/api/login&quot;, {<br>      username,<br>      password<br>    });<br>    return { isSuccess: true, sessionID: response.data as string };<br>  } catch (ex) {<br>    const error: AxiosError = ex;<br>    const { response } = error;<br>    if (!response) {<br>      return {<br>        isSuccess: false,<br>        errorType: &quot;network&quot;<br>      };<br>    }<br>    if (response.status === 401 || response.status === 403) {<br>      return {<br>        isSuccess: false,<br>        errorType: &quot;unauthorized&quot;,<br>        isBlocked: response.status === 403<br>      };<br>    }<br>    return {<br>      isSuccess: false,<br>      errorType: &quot;unexpected&quot;,<br>      serverMessage: response.data as string<br>    };<br>  }<br>}</pre><p>Basically, I wanted there two be two levels of discriminated union: first, if and only ifisSuccess is exactlyfalse, then I will have access to errorType (compare my Hedgehog&#39;s variant from Part One). This in turn is another singleton type that can let me distinguish between network error, authorization error, or unexpected error, each of which has its own data type.</p><p>It turned out nothing worked as I expected.await -ing the result of this function gives me a structure that does not change under any kind of guard. What’s more, errorType is not a singleton type of any kind but just plain string. So much for my grand plan!</p><p>But we did see that validateRequiredEmail function that was correctly returning singleton types and this login function. What what went wrong? After a few rounds of elimination, it turned out that:</p><p><em>TypeScript only sees singleton types in primitive literals that are directly returned, are directly passed as function arguments, or are directly assigned to constants, but </em><strong><em>not</em></strong><em> those nested in objects or arrays.</em></p><p>To illustrate what I mean, here are a few expressions:</p><pre>const literal = &quot;hedgehog&quot;;             // Type: &quot;hedgehog&quot;<br>const object = { kind: &quot;hedgehog&quot; };<br>const objectProperty = object.kind;     // Type: string<br>const array = [&quot;hedgehog&quot;];<br>const arrayItem = array[0];             // Type: string</pre><pre>const returnHedgehog = () =&gt; &quot;hedgehog&quot;;<br>const returnValue = returnHedgehog();           // Type: &quot;hedgehog&quot;</pre><pre>const returnObject = () =&gt; ({ kind : &quot;hedgehog&quot; });<br>const returnObjectProperty = returnObject().kind;   // Type: string</pre><pre>const returnArray = () =&gt; [&quot;hedgehog&quot;];<br>const returnArrayItem = returnArray().kind;         // Type: string</pre><p>I was a little disappointed at this, because I was hoping to get away with only the type annotation I absolutely needed. But with a bit of pedantry, I could tell TypeScript to treat object literal properties as singleton types.</p><pre>import { default as axios, AxiosError } from &quot;axios&quot;;<br>async function login(username: string, password: string) {<br>  try {<br>    /* ... */<br>    return { <br>      isSuccess: true as true, <br>      sessionID: response.data as string <br>    };<br>  } catch (ex) {<br>    /* ... */<br>    if (!response) {<br>      return {<br>        isSuccess: false as false,<br>        errorType: &quot;network&quot; as &quot;network&quot;<br>      };<br>    }<br>    if (response.status === 401 || response.status === 403) {<br>      return {<br>        isSuccess: false as false,<br>        errorType: &quot;unauthorized&quot; as &quot;unauthorized&quot;,<br>        isBlocked: response.status === 403<br>      };<br>    }<br>    return {<br>      isSuccess: false as false,<br>      errorType: &quot;unexpected&quot; as &quot;unexpected&quot;,<br>      serverMessage: response.data as string<br>    };<br>  }<br>}</pre><p><em>(Make sure </em><em>strictNullChecks is configured to </em><em>true in your </em><em>tsconfig.json , otherwise you may see different effects in what I’m demonstrating.)</em></p><p>Now I have my doubly-discriminated union! <em>[Edit: note in the block below, wherever we discriminate using </em><em>&amp;&amp;, each comment gives the type of the expression to the right of </em><em>&amp;&amp;, not the type of the entire expression. Thank you to </em><a href="https://medium.com/u/42ef98145a21"><em>Vadim Alferev</em></a><em> for pointing that out!]</em></p><pre>const result = await login(&#39;blah&#39;, &#39;blah&#39;);<br>result.isSuccess // Type: boolean</pre><pre>result.sessionID // Type: string|undefined<br>result.isSuccess &amp;&amp; result.sessionID // Type: string<br>!result.isSuccess &amp;&amp; result.sessionID // Type: undefined</pre><pre>// Type: &quot;network&quot;|&quot;unauthorized&quot;|&quot;unexpected&quot;|undefined<br>result.errorType<br>result.isSuccess &amp;&amp; result.errorType   // Type: undefined</pre><pre>// Type: &quot;network&quot;|&quot;unauthorized&quot;|&quot;unexpected&quot;<br>!result.isSuccess &amp;&amp; result.errorType</pre><pre>result.errorType === &quot;unexpected&quot; &amp;&amp; result.isSuccess // Type: false<br>result.errorType === void 0 &amp;&amp; result.isSuccess       // Type: true</pre><pre>result.errorType === &quot;unexpected&quot; &amp;&amp; result.isBlocked   // undefined<br>result.errorType === &quot;unauthorized&quot; &amp;&amp; return.isBlocked // boolean</pre><h4>Implicit vs explicit discriminated unions</h4><p>In the above example, I added a minimal type enforcement to get the discriminated union to work. But there was still something strange going on…</p><p>Earlier, with the Pet discriminated union, I wasn’t able to access a property that only existed on a type not matched by my type guard without a typing error (my Hedgehog couldn’t chase birds). But just now, note that I was able to get errorType directly without discriminating isSuccess first.</p><p>It turned out that the difference is because when TypeScript infers a discriminated union, it tries to “fill in the hole” such that the return type always has the same properties. Wherever the property isn’t defined in my object literal, TypeScript fills it with type undefined .</p><p>If, instead, I define the types of each outcome and then explicitly use it as the return type, I now have the same behavior as my Pet discriminated union. Here is how to do it:</p><pre>type SuccessfulLogin = {<br>  isSuccess: true;<br>  sessionID: string;<br>};</pre><pre>type UnauthorizedError = {<br>  isSuccess: false;<br>  errorType: &quot;unauthorized&quot;;<br>  isBlocked: boolean;<br>};</pre><pre>type NetworkError = {<br>  isSuccess: false;<br>  errorType: &quot;network&quot;;<br>};</pre><pre>type UnexpectedError = {<br>  isSuccess: false;<br>  errorType: &quot;unexpected&quot;;<br>  serverMessage: string;<br>};</pre><pre>async function login(<br>  username: string,<br>  password: string<br>): Promise&lt;<br>  SuccessfulLogin | UnauthorizedError | NetworkError | UnexpectedError<br>&gt; {<br>  try {<br>    /* ... */<br>    return { isSuccess: true, sessionID: response.data as string };<br>  } catch (ex) {<br>    /* ... */<br>    if (!response) {<br>      return {<br>        isSuccess: false,<br>        errorType: &quot;network&quot;<br>      };<br>    }<br>    if (response.status === 401 || response.status === 403) {<br>      return {<br>        isSuccess: false,<br>        errorType: &quot;unauthorized&quot;,<br>        isBlocked: response.status === 403<br>      };<br>    }<br>    return {<br>      isSuccess: false,<br>      errorType: &quot;unexpected&quot;,<br>      serverMessage: response.data as string<br>    };<br>  }<br>}</pre><p>Note also that with this pre-declaration, I <em>no longer need to force my object properties into singleton types </em>(no more of this true as true business!).</p><p>Now let’s look at some type testing. I am now unable to access type-specific properties without discriminating that type from the union first.</p><pre>(async () =&gt; {<br>  const result = await login(&quot;blah&quot;, &quot;blah&quot;);<br>  result.sessionID;                      // ERROR<br>  !result.isSuccess &amp;&amp; result.sessionID; // ERROR<br>  result.errorType;                      // ERROR<br>  !result.isSuccess &amp;&amp; result.errorType; // ERROR<br> <br>  if (!result.isSuccess) {<br>    result.errorType // OK<br>    result.errorType === &quot;unexpected&quot; &amp;&amp; result.isBlocked; // ERROR<br>    result.errorType === &quot;unauthorized&quot; &amp;&amp; result.isBlocked; // OK<br>  }<br>})();</pre><p>Again, this subtle difference in the behavior is a consequence of TypeScript’s inferred type not being quite as exact as our intended type. But we can see they they are both equal in safety: either a value is always undefined so you can’t really use it anyway, or the value cannot be accessed to begin with.</p><p>So here are two versions that represent a trade-off between brevity and strictness. I personally don’t see the implicit version as being problematic, and unless I feel that the outcomes are so complex that there needs to be explicit type documentation, I prefer the path of minimal type footprint.</p><h4>Unintended type narrowing</h4><p>TypeScript’s well-intended automatic type inference can get in your way of singleton types in other subtle ways. Here’s another example that I came across.</p><p>Suppose that you have a class that represents an input value and its computed validity. The input can be any string value, and you can pass any arbitrary validation function. To illustrate the problem related to typing, we don’t need to bother implementing the actual functionality.</p><pre>class Input {<br>  constructor( <br>    readonly defaultValue: string, <br>    readonly isValid?: (value: string) =&gt; boolean) {<br>  }<br>}</pre><p>Now suppose that I want to use singleton types for the input value (for instance to represent exact choices), I can make this class generic:</p><pre>class Input&lt;T extends string&gt; {<br>  constructor(<br>    readonly defaultValue: T,<br>    readonly isValid?: (value: T) =&gt; boolean) {<br>  }<br>}</pre><p>This works well when you pass an explicit union of singleton types. I have an input whose values are exact choices.</p><pre>const department = new Input(&quot;&quot; as &quot;&quot;|&quot;development&quot;|&quot;research&quot;);<br>department.defaultValue; // Type: &quot;&quot;|&quot;development&quot;|&quot;research&quot;;</pre><p>But now TypeScript’s rule that literals are treated as literal types will backfire on us. Let’s look at this one:</p><pre>const myInput = new Input(&quot;&quot;);<br>myInput.value   // Type: &quot;&quot;</pre><p>Uh oh, that’s not what we intended. There’s no reason why we would have an input with just &quot;&quot; as the only possible value! Instead, this is what we want:</p><pre>const myInput = new Input(&quot;&quot; as string) // I want any string!<br>myInput.value   // Type: string</pre><h4>Unintended type widening</h4><p>Brace yourselves, things are about to get a little crazy.</p><p>We will now start adding that second argument to our constructor: the validation predicate. Let’s suppose we add a simple “required” rule:</p><pre>const department = new Input(<br>  &quot;&quot; as &quot;&quot;|&quot;research&quot;|&quot;development&quot;,<br>  value =&gt; value.length &gt; 0 // required<br>);<br>department.defaultValue // Type: &quot;&quot;|&quot;research&quot;|&quot;development&quot;;</pre><p>The type of the input value is still correctly a union of singletons. Now let’s say I want to make the required rule reusable. Since the other uses might not be expecting exact choices, I make the parameter of requiredRule a string. So:</p><pre>const requiredRule = (value: string) =&gt; value.length &gt; 0;<br>const department = new Input(<br>  &quot;&quot; as &quot;&quot;|&quot;research&quot;|&quot;development&quot;,<br>  requiredRule<br>);<br>department.defaultValue // Type: string</pre><p>We just lost our singleton union!</p><p>I also want to add that, at this point, if this input value is being used to index an object with exact keys, you will get this totally cryptic error where the indexing takes place:</p><pre>const copyText = <br>{<br>  &quot;&quot;: &quot;Choose&quot;,<br>  &quot;research&quot;: &quot;Research&quot;,<br>  &quot;development&quot;: &quot;Development&quot;<br>};<br>copyText[department.defaultValue] // EXPLODES</pre><blockquote>Element implicitly has an ‘any’ type because type ‘<em>(the type of your structure)</em>’ has no index signature.</blockquote><p>What that message means is that TypeScript cannot index copyText — which expects one of the three singleton types as the index — with just any string value. The phrase <em>“has no index signature”</em> means just that: <em>“you can’t just index this with any old thing, please give me just the exact keys that I accept”</em>.</p><p>To understand what’s going on here, we need to re-visit the declaration of Input :</p><pre>class Input&lt;T extends string&gt; {<br>  constructor(<br>    readonly defaultValue: T,<br>    readonly isValid?: (value: T) =&gt; boolean) {<br>  }<br>}</pre><p>What is happening is that TypeScript is inferring the type parameter T of input from <em>both</em> the default value <em>and </em>the validation function. Since requiredRule explicitly accepts string, TypeScript infers T to be the broadest type that bothstring and the singleton string types satisfy, and that type is string .</p><p>Now let’s try this one:</p><pre>const requiredRule = (value: string) =&gt; value.length &gt; 0;<br>const department = new Input(<br>  &quot;&quot; as &quot;&quot;|&quot;research&quot;|&quot;development&quot;,<br>  value =&gt; requiredRule(value)<br>);<br>department.defaultValue // Type: &quot;&quot;|&quot;research&quot;|&quot;development&quot;</pre><p>We got the singleton union back! But why?</p><p>What’s now happening is that the validation predicate does not enforce a type: value =&gt; requiredRule( value ) does not annotate the type of the input, so TypeScript can’t use it to infer T. This makes the default value the sole determinant for T , and it is the singleton union.</p><p>While it is a beautiful idea that TypeScript can infer everything for us, in reality it doesn’t always work the way we want. Nevertheless, if we understand TypeScript’s tendencies in type inference, we can get the full intended power of the pattern if we give TypeScript a little nudge here and there.</p><h3>Conclusion</h3><p>I have shown how singleton types and discriminated unions can bring extra safety and traceability to JavaScript projects, while still embracing important JavaScript idioms. This is at least in principle. In practice, there are a few subtleties that are consequence of the opinions TypeScript forms when automatically inferring types in more complex scenarios. I have shown a couple of gotchas which others hopefully find helpful in troubleshooting similar obstacles.</p><p>I personally am a firm believer in the TypeScript project. Although I have demonstrated plenty of unintuitive artefacts, I still believe in the value that it promptly delivers when it gets all the information it needs. I am planning to write similar articles about other TypeScript patterns in practice, with the aim of realizing the tool’s full potential. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b20b1ec3a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to empower iterative design as a web developer]]></title>
            <link>https://medium.com/nyc-design/how-to-empower-iterative-design-as-a-web-developer-7a7b8f1097b9?source=rss-2c3699b38217------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a7b8f1097b9</guid>
            <category><![CDATA[continuous-improvement]]></category>
            <category><![CDATA[new-york]]></category>
            <category><![CDATA[code-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui-design]]></category>
            <dc:creator><![CDATA[Tar Viturawong]]></dc:creator>
            <pubDate>Tue, 25 Sep 2018 01:51:02 GMT</pubDate>
            <atom:updated>2018-09-26T17:40:53.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Empower Iterative Design as a Web Developer</h3><p><em>How code architecture can impact the innovative culture of your team</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FiGbyjPPczHBBvRs" /><figcaption>Designers can and <em>should</em> challenge developers more when we say something can’t be done! Photo by <a href="https://unsplash.com/@melvinthambi?utm_source=medium&amp;utm_medium=referral">Melvin Thambi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a web developer, I feel both amused and abashed whenever I have to explain to a designer that owing to architectural reasons, their idea of a simple change is a massive code surgery for us.</p><p>(To be precise, I <em>first</em> feel abashed admitting it, <em>then</em> I feel perversely amused watching my poor designer’s <em>what-on-earth-are-you-talking-about-it’s-so-simple</em> reaction as I nod sympathetically).</p><p>There are business and motivational costs when the codebase is stuck this way. Developers feel frustrated because of significant code reworking, and are more likely to resist late requirement changes in future. Designers feel frustrated because their creativity is constrained by some technicality that seems beyond common sense. Product owners are frustrated because the product cannot be refined in the way they envisioned. Teams become less agile, and the product misses out on the final touches that — taken together — might make that difference between a hit and a flop. In the extreme case, I have seen leadership getting burnt and calling for a return to the waterfall process where everything is locked down in advance.</p><p>Having inherited codebases in such a state (and having been guilty of plunging a couple into one myself), I have spent some time dissecting and bringing codebases out of this predicament. Here are some of the lessons I learnt.</p><h4>1. Avoid premature architectural optimization</h4><p>The truth that whichever web project you’re working on, the design rightly keeps changing as the product idea becomes validated and refined. If a project has just started, there is even more uncertainty. Unfortunately, the start of a project is also when developers feel most tempted to optimize the architecture prematurely, based on the incomplete picture of the product at the time.</p><p>When I first studied some very good web application architecture, my first reaction was <em>“wow, this is super bloated”</em>. Later, I would realize that the seemingly bloated boilerplate waslike an impressive — but empty — art museum waiting for art installations of various shapes and sizes to move in. Of course, empty art museums don’t usually get many visitors, and so all that engineering stunt seems pointless. But if you then try to shrink such a museum into a cozy little cafe, you will find that you’ll eventually have make do with just a third of the installations; another third wouldn’t fit and the last third wouldn’t be able to be safely housed. Oops.</p><h4>2. Anticipate reasonable, canonical requirement changes</h4><p>A resilient architecture therefore exploits low-effort practices to provide breathing room. It lets you support requirements which you can right now <em>reasonably expect</em> from canonical UI design patterns as seen on the interwebs. You do not need to — in fact, <em>should not</em>— actually implement these reasonably anticipated functionalities in advance, but you should consider an architecture that allows such functionalities to be built without a massive rewrite.</p><p>For example, whether or not your chat application’s current design includes an indicator that your conversant is typing shouldn’t have a big consequence in how you would separate concerns in the implementation. You anticipate that the design could end up either way, so you make sure that the “typing in progress” state is easily made accessible if needs be. Similarly, one could anticipate (again, not actually <em>implementing</em>) canonical design variations like:</p><ul><li>asynchronous validation when building synchronous validation</li><li>validation-on-type when building validation-on-blur</li><li>upload progress display even when building a static spinner</li><li>visual elements with dynamic visibility transitioning their entrance and exit</li><li>swapping a component for another (e.g. a radio group for a dropdown, a number-based paginator for a dot-based paginator)</li><li>relayouting — visual elements that were together aren’t together anymore. This is especially important if they happen to share state.</li><li>state persistence — visual elements with dynamic visibility might change from discarding its state when it disappears then reappears to persisting its previous state.</li></ul><h4>3. Choose third party libraries that don’t lock you in over multiple concerns</h4><p>We often rely on third party libraries because we know they have been battle-tested to solve certain problems well. If such libraries do not separate concerns the way you do, you may end up being locked into a UI design pattern that your designer does not agree with.</p><p>Libraries can force their opinion of styling, UI state transition or domain logic on you, thereby constraining your code’s ability to adopt more flexible requirements. For example, if you depend on a validation library for validation rules, but it also forces opinion on how to manage error state, you are locking yourself in.</p><p>That said, not all teams put equal emphasis on all design concerns, and sometimes things are just good enough. If you sense that your organization is OK with not fine-tuning UI aspect that is locked by your thid party library, you might be able to get away with it. Otherwise, go for libraries that do things well over one concern but are not opinionated in the others.</p><p>It is also possible that a framework forces you into expressing — and therefore reasoning — about your business intentions in a way that is secondary to their syntax. If your code expresses more of a framework’s formalism than a your application’s intentions, consider a different solution that leaves less technical footprint.</p><h4>4. Use resilient code patterns</h4><p>Another thing that I have learnt is to look out framework-specific implementation pattern that looks like it’s going to be highly sensitive to arbitrary changes.</p><p>If you know React, you’ll have heard of its <a href="https://reactjs.org/docs/lifting-state-up.html">state lifting pattern</a>. As a React lover, I think this pattern is unfortunately not very resilient. How far up you lift a state essentially depends on your component hierarchy and where it is shared. This is where small change in requirement can really wreak havoc in your React codebase. Because of this, I personally prefer to manage state exclusively using <a href="https://mobx.js.org/index.html">MobX</a>, and lift <em>any </em>state that can be reasonably expected to be shared out of the React component hierarchy altogether. But this is quite its own topic.</p><p>If the paragraph above was complete gobbledygook, watch out for implementation patterns that make you think of Jenga: if a codebase looks like it will come tumbling down with the next requirement change, re-think how it’s built. If possible, avoid building a Jenga tower to begin with.</p><h4>Conclusion</h4><p>Iterating design, development and validation and minimizing the time through each iteration is how businesses can innovate at scale. By anticipating reasonably expected requirement changes and choosing an architecture that has the potential to support such changes, we developers can do our part in empowering iterative design, encourage experimentation, and contribute to an environment where everyone in the team feels inspired.</p><p>More recently, I worked with a designer that would have none of <em>oh-its-too-difficult-technically-but-you-don’t-get-it</em> attitude. That was a truly inspiring moment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a7b8f1097b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nyc-design/how-to-empower-iterative-design-as-a-web-developer-7a7b8f1097b9">How to empower iterative design as a web developer</a> was originally published in <a href="https://medium.com/nyc-design">NYC Design</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>