<?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 Andrew Philips on Medium]]></title>
        <description><![CDATA[Stories by Andrew Philips on Medium]]></description>
        <link>https://medium.com/@andrewphilips?source=rss-c67b173cb351------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JbwiPWST_qUguFlW.jpg</url>
            <title>Stories by Andrew Philips on Medium</title>
            <link>https://medium.com/@andrewphilips?source=rss-c67b173cb351------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:06:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewphilips/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[A Desktop Lab]]></title>
            <link>https://medium.com/@andrewphilips/a-desktop-lab-815264df2cea?source=rss-c67b173cb351------2</link>
            <guid isPermaLink="false">https://medium.com/p/815264df2cea</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[freebsd]]></category>
            <dc:creator><![CDATA[Andrew Philips]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 07:57:43 GMT</pubDate>
            <atom:updated>2024-03-17T07:57:43.013Z</atom:updated>
            <content:encoded><![CDATA[<h4>Home Lab</h4><h4>Home Grown Router, Part I</h4><p><em>Part I of a three part series on building my bespoke network router.</em></p><p>In my <a href="https://medium.com/@andrewphilips/build-my-own-router-8e120fc17274">Introduction</a>, I laid out the requirements for the edge router I’m building for my home network. It must run all of the services my current router provides, go faster, be serviceable, and allow for future experimentation. In the end, I specified the hardware (Protectli SFF) and software (Proxmox and FreeBSD) that I’d be using.</p><p>This article explores setting up a Desktop Lab for prototyping the router. The lab includes the new computer with Proxmox and FreeBSD VMs, a Raspberry Pi as a console terminal, a cellular data modem and a Wireguard app for VPN access. With the lab, I can prototype various configurations and experiment with features required for the final router. The Raspberry Pi serves two purposes: (1) a console terminal into the Protectli via USB—no matter what happens to the network or VMs, I can get into Proxmox through that, and (2) a backdoor (second route) into my network through a cellular modem and a VPN. The backdoor will come in handy if I bork my main router as I now have another path into my network. During prototyping and production, I have to be able to service the network devices while off site.</p><figure><img alt="Image of Desktop Lab with NUC, Proxmox, VMs, Raspberry Pi, Switch and Cellular Modem." src="https://cdn-images-1.medium.com/max/562/1*uxU-DI2fhf023En9toErrQ.png" /><figcaption>Wire Diagram of the logical structure for the desktop lab. Redundant pathways into the hardware and software are crucial for continuing to work on the router when it has been misconfigured. Image by Author.</figcaption></figure><h3>Machine Setup</h3><p>Unboxing the Protectli Vault went almost perfectly. One challenge I had was connecting to its console port. We have an all Apple hardware household and the USB to console port cable won’t take connections from Apple hardware. We e-cycled all of our old computer equipment long ago including HDMI screens. I grabbed an unused Raspberry Pi, formatted its SD Card with FreeBSD, tricked the Pi into speaking to my MacBook Pro over ethernet, and then consoled in from the Pi. Keep in mind, this was all to get into the console on the Vault.</p><p>After I connected through to the Vault’s console, BIOS setup and Proxmox install from a USB drive was a piece of cake. I made sure to create random complex passwords for the BIOS admin and user accounts and the Proxmox root account knowing I’d probably fail to do it later. A lot of people purchase Protectli Vaults to run Proxmox, so Protectli posted <a href="https://kb.protectli.com/kb/proxmox-ve-on-the-vault/">helpful instructions</a> with the steps required to do the installation.</p><figure><img alt="Web browser showing Proxmox management GUI focused on panel containing ISO images." src="https://cdn-images-1.medium.com/max/1024/1*Ozg_V5Q6xW0ujmR4Ltlxqg.png" /><figcaption>Proxmox management GUI with panel showing ISO images. Image by Author.</figcaption></figure><p>With Proxmox running, I wired my MacBook to one of the Vault’s ethernet ports, brought up a browser, and followed the initial Proxmox configuration steps. After configuration, I navigated to the <em>local</em> storage screen where I found the <em>ISO Images</em> panel and downloaded a stable version of FreeBSD. Proxmox let me enter the Checksum for the downloaded ISOs as a safety and a security check.</p><p>Using the FreeBSD ISO I created a new VM running FreeBSD OS and went through that set up process. With a configured instance of FreeBSD running, I took one last step and made a Template out of it. If you examine the above image, you can see I have three templates. That’s because it took me three tries to get the template I liked. I left the others there just because. You can also see there are five VMs running and two shutdown. Between templates and VM cloning, Virtual Machine creation is like eating popcorn—you can have as much as you want.</p><figure><img alt="Web browser showing Proxmox management GUI focused on panel accessing a virtual machine’s console." src="https://cdn-images-1.medium.com/max/1024/1*xi5I5klS5MvmEiD_pMNSDg.png" /><figcaption>Proxmox management GUI with panel accessing a virtual machine’s console. Image by Author.</figcaption></figure><h3>Redundant Access</h3><p>Experiment enough with network equipment and you quickly realize you need multiple pathways into it, especially while you’re learning. When working remotely, multiple pathways are even more critical.</p><p>Although I had a trip scheduled in the midst of this, I didn’t want to lose a couple of weeks working on the system. More importantly, once the router is operational redundant remote access via a VPN is critical. To address this, I settled on the following: (1) a Raspberry Pi connected to the Protectli’s console port, (2) a new to me 10-port 1Gbps managed switch (VLANs!), (3) a cellular data modem I had been meaning to use for redundant backup but hadn’t got around to it yet, (4) a couple of VMs (Stargate 1 and Stargate 2) running FreeBSD with default routes to my main router and the cellular modem, respectively, (5) a NAS with VPN support, (6) for VPN, Wireguard on the Pi, the two Stargate VMs, and the NAS. The wire diagram at the top of this article contains this structure.</p><p>These virtual and real machines each have multiple static addresses for various VLANs. For example, Stargate 1 has static addresses for five VLANs: (1) Engineering 10.3.25.6/24, (2) local to Switch-3 172.20.50.6/24, (3) for cellular modem (to WAN2) 192.168.90.6/24, (4) for simulated cable modem (to WAN1) 10.4.200.6/24, (5) internal to Proxmox 172.20.55.6/24.</p><p>The Raspberry Pi has four of these address which all end in .8 instead of .6. Making all of the devices static and each device have their own low # (.6 vs .8) means I can memorize VLAN prefixes and device IDs and then combine them when I want to ssh into them. The Pi doesn’t have a fifth address because that last one in Stargate 1 is internal to and only reachable by PVE and the VMs.</p><figure><img alt="Four connected devices—switch, Protectli, Raspberry Pi, Cellular Modem—all surrounding a pile of coiled ethernet wires." src="https://cdn-images-1.medium.com/max/1024/1*oFYWdbnmbYHcHrqGf5csLQ.jpeg" /><figcaption>Desktop Lab with switch, Protectli, Raspberry Pi and cellular modem connected by a coil of ethernet cables. Note the labels on each cable matching switchport to device. Pi consoled into NUC. Image by Author.</figcaption></figure><p>The day before I left, I had a chance to test remoting into this set up. Earlier in the day I had played around with my main firewall configuration and wanted to reset it to the last known good configuration. During the reset, the internet would be down. My wife was still using the network. Rather than wait around, I headed out for some errands and once she left the house, used my phone to connect through the cellular modem via Wireguard (backdoor), rebooted the main firewall (frontdoor) and checked that I still had internal network connectivity via the VPN. I did. Test passed!</p><p>While traveling, I have VPNed into my home network, managed a few ongoing jobs (new NAS backups) and retested the connections between all the various devices in the desktop lab.</p><h3>Final Prototype Configuration</h3><p>I left before I had a chance to setup the virtual network hardware for the VMs containing the router and DNS/DHCP. Using the VPN I completed those configurations the other night. Now, in Proxmox I have four VMs (router, dnsmasq, two landing pads). Next up, I’ll configure the dnsmasq VM to handle DHCP and DNS. Understand, this is prototyping and probably won’t be the final production configuration.</p><p><em>Soon—Part II: </em><em>dnsmasq in FreeBSD to serve DHCP addresses and DNS.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815264df2cea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building My Own Router]]></title>
            <link>https://medium.com/@andrewphilips/build-my-own-router-8e120fc17274?source=rss-c67b173cb351------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e120fc17274</guid>
            <category><![CDATA[router]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[hypervisors]]></category>
            <category><![CDATA[freebsd]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Andrew Philips]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 22:07:44 GMT</pubDate>
            <atom:updated>2024-03-17T08:00:10.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>Home Lab</h4><h4>Home Grown Router, Introduction</h4><p><em>Introduction to a three part series on building my bespoke network router.</em></p><p>A decade ago, during our home renovation an IT subcontractor recommended commercial equipment for our network. He promised to help me set it up, and then promptly disappeared leaving me to my own devices. One painful learning curve later and we had a solid home network backed by a 48 port PoE switch supporting virtual LANs and multiple WiFi access points. After a couple of years I built my own home automation system from scratch. Over time, I upgraded my cable modem to one that supports 1Gbps download speed and assigned most of our IoT equipment to internal only VLANs. It’s a complex system and my end-of-life, no longer supported router has buckled under the weight of it all. The other day I checked download speed—it was 118Mbps, 1/8th of what I should have.</p><p>It’s time to upgrade. But, to what? More importantly, what do I need?</p><h3>Requirements</h3><ol><li>A router capable of at least 1Gbps with full security enabled.</li><li>Easy security management for devices, VLANs, and people.</li><li>Reliable upgrade and patching.</li><li>Current router feature coverage : DHCP, DNS, NTP, VLANs, etc.</li></ol><p>There are plenty of prosumer routers out there that meet this list of requirements and picking one would save me plenty of time and possibly money. However, buying one means I have to live with other people’s decisions. Invariably, no matter how good something is, it’s design is a compromise to meet a certain need. Most SMB networking equipment abstracts away complexity and simplifies operations. I don’t want that. I want the complexity. Learning new things sparks joy.</p><p>So, I have a fifth requirement:</p><p>5. Understand and have expert level control over router behavior.</p><h3>Options</h3><p>Packaged prosumer hardware routers are out. I’m not going to buy a five figure Cisco or Juniper firewall/router. Enter software on a box.</p><p>There are plenty of software-based router/firewalls available for purchase or through open source. I could even run one on an old machine sitting around my house. Choices for open source-ish solutions include: pfSense, OPNsense, OpenWRT. With these packages, however, I’m still buying into someone else’s design choices (violates Req 5). They do make things easier for system management through their GUIs and their well tested releases (meets Req 2 &amp; 3).</p><p>Digging further, I found out two things. One, pfSense and OPNsense are based upon BSD’s pf library (<strong>P</strong>acket <strong>F</strong>ilter). Two, they are packaged to run on “bare metal” just like an operating system. In fact, their release includes the operating system FreeBSD and they run on top of it. The name <em>pfSense</em> comes from “Making sense of pf”. Rather than commit to a packaged software router, I can install FreeBSD on any piece of equipment, run a handful of services and have my bespoke router. Why eat someone else’s dog food when I can make and eat my own?</p><p>One last twist: I want to run my bespoke software router as a Virtual Machine. Why? First, the early learning phase for this project means I’m going to be playing with a lot of knobs and levers (meets Req 5). Installing and re-installing software including an operating system takes time. Speeding up the reinstallation process means faster learning cycles, more freedom to fail, and ultimately a shorter time to stand up the final router. Second, an operational router requires patching and upgrading. With a VM I can snapshot or fully clone the current running configuration, apply the changes <em>to the copy</em> and test before I deploy once it all looks good. If I find a problem after I’ve deployed, two button clicks and I’ve rolled back to the previous working version (meets Req 3).</p><figure><img alt="Small Form Factor computer with attached USB cable" src="https://cdn-images-1.medium.com/max/1024/1*a1gyZQaI8GPw3PwVHPXc4w.jpeg" /><figcaption>Small Form Factor (SFF) computer with USB console cable attached. Photo by Author.</figcaption></figure><h3>Final Configuration</h3><p><em>If I must eat my own dog food, can it at least be gourmet?</em></p><p>Here’s my planned build:</p><ol><li>Fanless <a href="https://en.wikipedia.org/wiki/Small_form_factor_(desktop_and_motherboard)">SFF</a> computer with 1TB SSD &amp; 6 NICs (room to expand)</li><li>Proxmox Virtual Environment running VM(s)</li><li>FreeBSD for the router’s operating system</li><li>pf for the firewall and router</li><li>dnsmasq for DHCP and DNS (we can talk about Pi-hole later)</li><li>Other required services come with the OS (ntp, etc.)</li><li><a href="https://tailscale.com/">Tailscale</a> VPN running in a <a href="https://en.wikipedia.org/wiki/FreeBSD_jail">FreeBSD Jail</a> for remote management</li></ol><p>The SFF will have enough processing power to handle the hypervisor, the VM(s), the software router and still run at 1Gbps (Req 1). As discussed earlier, this build meets all of the other requirements. Most importantly, it meets Requirement 5 allowing me to dig in deep, learn and have complete control over my system.</p><p>I’m excited to build this router. It’s a significant upgrade to the current one. It also provides a platform facilitating experiments with new software and hardware—a home lab, something I hadn’t appreciated the value of until now. That said, my primary goal is a drop in replacement for my current router and that’s what I’m focused on. Expanding features comes later.</p><p><em>Next up—</em><a href="https://medium.com/@andrewphilips/a-desktop-lab-815264df2cea"><em>Part I: A Desktop Lab</em></a><em> &amp; setting up Protectli, Proxmox, and FreeBSD</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e120fc17274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Narrowing Multiple Return Types in TypeScript]]></title>
            <link>https://medium.com/@andrewphilips/narrowing-multiple-return-types-in-typescript-6bb96447a105?source=rss-c67b173cb351------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb96447a105</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Philips]]></dc:creator>
            <pubDate>Mon, 01 May 2023 02:58:51 GMT</pubDate>
            <atom:updated>2024-03-08T02:56:20.839Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming Notes</h4><h3>Narrow Multiple Return Types in TypeScript</h3><figure><img alt="Image of two hands — one holding an orange and the other holding an apple." src="https://cdn-images-1.medium.com/max/510/1*1QlQwrzoQUbcCu-XMpEh1w.jpeg" /><figcaption>Orange or Apple?</figcaption></figure><pre>// multiple return types<br>function getFruit({withCitrus: boolean}): Apples | Oranges;<br><br>// Why can&#39;t we write this?! We know Oranges are returned<br>var fruit: Oranges = getFruit({ withCitrus: true }); // error</pre><p>Function getFruit fetches us a bag of Apples or Oranges. At compile time, as developers we know the function returns Oranges because we asked for them. Unfortunately, the compiler doesn&#39;t know this. To fix the error, the standard recommendation is to use a <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates">Type Guard</a> to narrow the type. This requires extra and seemingly unnecessary code.</p><pre>// type guard distinguishes between Apples and Oranges<br>function isOranges(fruit: Apples | Oranges): fruit is Oranges {<br>  return &quot;VitaminC&quot; in (fruit as Oranges);<br>}<br><br>var fruits: Apples | Oranges = getFruit({withCitrus: true);<br>if (isOranges(fruits)) {<br>  // type guard narrowed the type to Oranges<br>  var oranges: Oranges = fruits; // ok, no compilation error<br>}</pre><p>The thing is <strong>we know the returned fruit type at compile time</strong>; why should we use a type guard? Can we skip it? To do that, we need to rewrite the getFruit function.</p><p>In this <a href="https://dev.to/maurerkrisztian/typesafe-multiple-return-types-wuith-typescript-54j9">article</a> Maurer Krisztián shows how to use a Generic to connect a function’s arguments to its return type.</p><pre>type FruitType&lt;T&gt; =<br>  T extends { withCitrus: false } ? Apples :<br>  T extends { withCitrus: true | undefined } ? Oranges :<br>  Oranges;<br><br>function getFruit&lt;T extends { withCitrus: boolean }&gt;(opt?: T): FruitType&lt;T&gt;;<br><br>var apples:   Apples  = getFruit({withCitrus: false}); // ok<br>var oranges1: Oranges = getFruit({withCitrus: true});  // ok<br>var oranges2: Oranges = getFruit();                    // ok</pre><p>Using Krisztián’s formulation, we see at compile time how options passed to getFruit narrow the return type to that of the expected type. This is a great start, let&#39;s continue building upon it.</p><h4>Avoid Type Casting</h4><p>When we implement the function definition returning FruitType&lt;T&gt; we find it requires an internal type cast (ugh). If we add an overload function, we can continue to narrow the return type while separating it from the implementation.</p><pre>interface IOptions { withCitrus?: boolean };<br>const DEFAULT_FRUIT_OPTS = { withCitrus: true } as const;<br><br>function getFruit&lt;T&gt;(opt?: T extends IOptions ? T : never): FruitType&lt;T&gt;;<br>function getFruit(opts?: IOptions)<br>{<br>  const _opts = { ...DEFAULT_FRUIT_OPTS, ...opts };<br>  return _opts.withCitrus ? bagOfOranges : bagOfApples;<br>}</pre><p>Here’s a <a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgIIAd0BsIGdkDeAsAFDLnIID2AruAFzIg0C2ARtADSkWVVZUojAERQIAE2HIAPsmEBzMRBBTZwgJ4QsAgO7DuJAL4BuUqVCRYiFAHkocEPLyEeFanTCNm7Lq-LUBITlBBydVOUUIZX0-ZAA1YDA4FlAAYUYwKBoIAxMzEgtoeCRkAEkAMSzEm3QwYCoQfGIyCh1EgAtUxKzcAH5GNip+CAdc0xJSakawZAARAFFy1ABVABkAFQB9coAlZdKtmwAFdeQAXkJkNrBO7ppcDKyUPImSKdwZjGwIAGVk74eaEwOHwFwIfA8jAAzJw+IERGJJMhDMg4Ph3mBxhjkHZQr9-iDGLjHM4wRCGMgACywgKCEQhEn6eKJZJpR7ZZGo9END7jUhgdToFCVGiJdaCiAAHnWAD5zrFThAAB6QEDiJpXDpdTL3RjwLC4Z7IXpAgHIegK5DK1Xqy7XW46wE6lCyOjiCAwUASTkm4lOfAWlrkP14PkkAD04eQ8ygUEEpEjyHFQuQAHIviCZDj7CTcKnkMB8CAqDM0bhgPIQHA2DhkGAqHWJWmRWKJdKZamAHQJqPkZModPAvD5wtMEtc8uV6u1+uNlOpltgfvtrsACgATFD1+vSDA6Ag6g1kE4wIvpVaVcpbRUqmAaofGjLV1Ran1GOsAJSMRfL2WkZq8NimwvmAoJ2lqdxOk8sLtGiqT8HSwQ5mEsKdmhIH4C8sRiGANBQCAyDAa+nb2tqPTGtmeJ-CwZqMBm+I0SC4yGPkib9pQaKlgAblQwC2tAcZQLCbA0DMCAOMg7R8SgJbtNAVqxoIuC7vuD7HhAp63psADqWqcee1pXvgN6inetT1I+z6vv0SZfsgP5tn+JAAW4PIzERoHnOBNxkbqdbQZJcEIUEwgMihyBoZ2GHImGvA4XhBGrh5uAkRBjoUSG1G0aaOBZSCH5cvZt6-jKzGsVG5SqRZyBUFx0ACHA4gcbUeHOOgcZClAc7ODoUm1jhcCgKA8jdcguBwDAGnqCpIAHtVJ6LjpHQ2HVUANeIBmXmqxmLveFm4E+GE2Z+37FY5pUzXNR4LVpuk3Ct9VUI1VmgTZJnVOZPIfv+sRAdFZKkZB7I5IFuDwfCSF4kykXRVhQbIPF+HIElGGpT5kEZchDHZfReV4B+ZUkEAA">TS Playground</a> showing the error and the overload.</p><h4>Allow Other Options</h4><p>Adding another option does not interfere with return type narrowing.</p><pre>interface IOptions {<br>    withCitrus?: boolean,<br>    hasColor?: Apples[&#39;color&#39;] | Oranges[&#39;color&#39;],<br>};<br><br>var apples:   Apples  = getFruit({withCitrus: false, hasColor: &quot;red&quot;});   // ok<br>var oranges1: Oranges = getFruit({withCitrus: true, hasColor: &quot;orange&quot;}); // ok<br>var oranges2: Oranges = getFruit({hasColor: &quot;red&quot;});                      // ok</pre><h4>Can We Always Narrow?</h4><p>Regardless of how well we refine the TypeScript, there are still some situations when the return type cannot be narrowed.</p><pre>var opts5 = { withCitrus: false };          // boolean<br>var apple5: Apples = getFruit(opts);        // error<br><br>var opts6: IOptions = { withCitrus: true }; // boolean<br>var orange6: Oranges = getFruit(opts);      // error<br><br>var opts7 = { withCitrus: false } as const; // false<br>var apple7: Apples = getFruit(opts);        // ok</pre><p>When assigning an object to a variable, TypeScript generalizes the object. opts5 gets type { withCitrus: boolean } and therefore the return type is Apples | Oranges. This is the same result for opts6. For opts7, we use as const to convert the object to a <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-inference">type literal</a>, and we once again have return type narrowed.</p><h4>Edge Case Typing</h4><p>We have a couple of potential edge cases with the type definition of FruitType&lt;T&gt; that can cause some bugs: (1) single source of truth for the default option value and (2) triggering a <a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types">Distributive Conditional Type</a>.</p><p>See this <a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgIIAd0BsIGdkDeAvgNwCwAUKJLIigPJRwgDmehpllYAnuigDEoAV2BgAKnwgAecQD5kAXkrJk45BAAekEABN8BZAHcxACwDCYkbgD8ALmSgY0ZACFkRZDZWrkAIwB7AJxmDW0IPXx3G2RGZjZ8AB80TBx8Ox9Vdy0dfWRhPQgYUAhdZGSwERQYuNZ2DIpfFOx6n1qE8gouCgB6ACpkAFFdNmRzOFw8boFgKFwwABpkMFMUXSK4YSwwZAA3OCxhFACYZAADSqOzxxBzgBFBgVQAVQAZcQB9AQAlZ4BJT70AAK4gAygA6EwrSyXXDXAC2wnmyHhcDACFM3FW50uEGuoGW2LOQlEEik13WxRAYmAAVuEUqPHO2XCkXyhSppXKyyqXliTDqcPBlG+EAAjqIoKAWIS8CgwEYAnsDkd8GAlX4UABrCDoHYE3A8EAIZAIKAQNHsUIBTABKBgApiJkwO3+YQsXDCiiobamALu0zGFAIf1YMq6AIIYTwhmE4D4c0S2YQGPgJZGFC4P1bMrmoxSyDnEliST8a7q5DmrA8Sh05APJ5vT4-f6AkEQqEWKxI5DMXRLFbQCB+HhLM0WwtwZC4aU4af+qBIZAnHnCFZeyjibGTEN6Ry4XBHffIJOFw9+MBzvsaCZMivw+O4BxGVa3M5OFyuCkQGgPkDsVxKHjc5AmCC0QDOcEQKCEIIOPKdHTrFcLl5ZJ4CwSZIOQP5bhWYCEAmCB0xQUw4F2FA4EoO540qYA-DXYByLGOldBpOkDjUKRkAAbQARgAXSgrdgLgGBnAQMB8D9IxZRuGgQA4gAKHcWIASmWaAFKgGsKBtaA0VdYCIH2Q5LV0KC-h2UjMAiNUlXNB0oFw7EQygc0JOWLiCTw-AZwdNFaRAL07l1CJWNYfJ0DrQdkDYf8pRNXh+HySYygrdZfxKWSHOEJzPP4AdTHw0MynHS1KCneiWCgn0Vn9FhAxAAIdnmBLLyZf8kAPOBtOQF0oDjfAtDgeEWiWHAwAAcnwMiAmANKpRYNgpVYCrbkQBB5oZDjWNauiGLpBwzm40DYP4sJcnwbjXHOmJwXuyDul45AAFpkFMMAwHQJ8eh6Ix-vBJK8DNYA9SweJwTtFgegjBBcB6Ui9FArUegAJh6XdWLAQKDheoHPQ++EsAAYl22j6Ox8iXsxtiFKwPGpFwSg+h6bpd2RBsXneL5fgBD5gTBJRCGMMwYWsBxcQ8Xt8HZsBOm4LjizJfgZk0UpZAUZRGjUC6woMEXoW7WwHA-Ab3E8bxtdUE6YPA86cj1nibr5dp2GSDAWnSTI3F1tkCkpEoygqKQV05psedbfn20hUWja8b3XfSZo0mQBpVETzogA">TS Playground</a> for a deeper explanation.</p><h4>Final Form</h4><p>Tying it all together.</p><pre>type FruitType&lt;T&gt; =<br>  T extends { withCitrus?: infer B } ?<br>    [boolean] extends [B] ? Oranges | Apples :<br>    B extends undefined | typeof DEFAULT_FRUIT_OPTS.withCitrus ?<br>    Oranges : Apples :<br>  Oranges;<br><br>function getFruit&lt;T&gt;(opt?: T extends IOptions ? T : never): FruitType&lt;T&gt;;<br>function getFruit(opts?: IOptions)<br>{<br>  const _opts = { ...DEFAULT_FRUIT_OPTS, ...opts };<br>  return _opts.withCitrus ? bagOfOranges : bagOfApples;<br>}</pre><p>Find the complete code and tests for return type narrowing in this <a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgIIAd0BsIGdkDeAsAFDLnIID2AruAFzIg0C2ARtADSkWVVZUojAERQIAE2HIAPsmEBzMRBBTZwgJ4QsAgO7DuJAL4BuUqVCRYiFAHkocEPLyEeFanTCNm7Lq-LUBITlBBydVOUUIZX0-ZAA1YDA4FlAAYUYwKBoIAxMzEgtoeCRkAEkbdDBgKhB8YjIKHUSAC1TErNwAfkY2Kn4IBwNeZrhcVP5BbrRMHFwAbQByAMEFgF0ZZDtQvEXlqDXc0xJSalqwZAARAFEAMVQAVQAZABUAfRuAJXvSt5sABWeAGVkABeQjIJpgVrtGi4DJZFCGZCjPhnI75U64c4YbAQQHJXH4UHIOYEPgeRgAZk4fECIjEkmQhk4ZPcDGQAFYaXsRJFokyWeT2QB2bkTIIaLS6KSGdYozFgI4Kzb2Rx4gmzYmkoWeZAAFjFdOCqrCNISSRSIHSyEy2QFrNo7IAbIbBLylCozYlkml4XbZcj8Ar0SQwOp0CgbllEs9wxAADzPAB8oNiz2QEAAHpAQOI6hCWm1bV1GKAYNBkAAhJnITqxXhzXr9BzrLM5vMkyvrToq7b4WQ4zX0esUatt5QdujiCAwUASDZhiNUGCXW4PF7vL4-V7-IEAOkh0OLtd7avww4avHIg+cF94WzPIdIMDoCCqNWQTjAUZoiUTSYACioSopnTcdc3wcpKmqWoT3TLwIAAN2gABKRgfxjON-yOF8QDfGDPwgb9ozAIDKhLMoKnfWoUNIepeGVV5gLAfAwTJPcOOuO4njeT5vl+AFARpDi92Y-A8mOS9kDEMAaCgEBkAAkdyCY8iD0LGF8DrKT7xNdUWEJOYHycfEDNmPdZ1zUpcyzIDQRTABCVSWL3EYxnFGRZCoPc9lBMFnNwVzRnGQIUPWO8r2vGZ9MMm9TMJCzQHEazp0zOyQUcgKgvcwJPOQbzfJBfyxOykLBDC2IUKOQx8kQuAoGRaLcAARkYaZCXIMEvww0iCEPIsOkYeAsFwCBDCq0g6oauAmoAJjam8iS6oieoAvqNOLIa4BGnJkDcsqJQZYRxqOKb8r0lrGGM5xluI39ev6zS-TGiaSDOkIz3m08nFYwi7sSADXvei7KSui7iW6ki1v28V3SiFQTsm+rzr7PUwb7CGVqh9aoQG2FGCnGc53ERHJNIAB6cnkCuTMNQgK6AGkCyhZBhtGxT5RqLEaSwRJoG22i3uRsTiTJR7NtZ7bRppGGjQUD1jsDVEsVO5HHj5+wsDa3hFsx-7SLEoHkesyxRvwmp0JI2MI3jKDqNwJNVYai4ZzgGgsF1K8euthNCcsiRHfySnqdpsz6epqAoEEZnmmQJscAcRTFxQYB8CcEB+awMVpwhQQAGtcEF97yOa0WY7xuFJZ2mXgthiIFaVhUJLOrNWvazVbtWsTmqqyLeGD6Ao6gJGGrAdA2+T5d8pL9Tcc04w+-7qn44GEAg6pmm6cYK5I+jw8476BOFIA5PkFTwiM817OUB0fPC5H6eWK+u2YN+sWNsGm0ESZJ2M0zL7rq-UhvdMiT9e6LwHrvYeklg6bzDozGOX87QAU5mcHmGsBYPzEpSMu4tP5s0RI3LmioH5ZlBu3G6f0u7kUpOAiBVMqB5wxFzfoe4BDyDWgAcQ9DeRgrcaTXWunw-+NIPgSF4X-SkpMgA">TS Playground</a>.</p><p>In this article we explain how to narrow a function’s multiple return types using its argument list; we show how to inform the compiler which return type the caller expects. We do this in a type safe manner and avoid superfluous type casting. We encourage extra steps to avoid bugs when changing types and defaults. Finally, we explore various edge cases where return type narrowing requires extra focus by using type literals or type guards.</p><p>Please comment and let me know what you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb96447a105" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>