<?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 Adrien Gautier on Medium]]></title>
        <description><![CDATA[Stories by Adrien Gautier on Medium]]></description>
        <link>https://medium.com/@adrgautier?source=rss-c04ba6407220------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ukE1M6fY6tNm81elpnYthw.jpeg</url>
            <title>Stories by Adrien Gautier on Medium</title>
            <link>https://medium.com/@adrgautier?source=rss-c04ba6407220------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 20:14:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adrgautier/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[TypeScript “object” doesn’t make sense]]></title>
            <link>https://medium.com/ekino-france/typescript-object-doesnt-make-sense-fc95b6c663f9?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc95b6c663f9</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 09:11:51 GMT</pubDate>
            <atom:updated>2026-01-16T09:11:51.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JuyFrrtSHcOuToXx7-dZA.png" /></figure><h3>What is an object in JavaScript?</h3><p>You’ll often hear that “everything is an object” in JavaScript — but that’s not quite true. Primitives like string, number, or boolean are <em>not</em> objects. The confusion likely comes from the fact that primitives <em>behave</em> like objects in many cases.</p><p>This is due to JavaScript’s auto-boxing mechanism:</p><blockquote>Primitives have no methods but still behave as if they do. When properties are accessed on primitives, JavaScript <em>auto-boxes</em> the value into a wrapper object and accesses the property on that object instead. — <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">MDN</a></blockquote><p>Take strings, for example. A primitive string and a String object differ in two key ways.</p><p>First, their types are different:</p><pre>console.log(typeof &#39;Hello&#39;) // &#39;string&#39;<br>console.log(typeof new String(&#39;world!&#39;)) // &#39;object&#39;</pre><p>Second, you can’t add properties to a primitive:</p><pre>const stringPrimitive = &#39;foo&#39;<br><br>// attempt to add a property<br>stringPrimitive.foo = &#39;bar&#39;<br><br>// the property is silently dropped<br>console.log(stringPrimitive.foo) // undefined</pre><h3>TypeScript approach</h3><p>TypeScript needs to reflect JavaScript’s behaviour: a value’s <em>shape</em> (<strong>how</strong> it can be used) isn’t always tied to its <em>type</em> (<strong>what</strong> it is). TypeScript separates these two concerns.</p><h4>“How”: Structural Typing Example</h4><p>Consider this logger function:</p><pre>function logLength(value: { length: number }) {<br>  if(typeof value === &#39;string&#39;) {<br>    console.log(&#39;String length is:&#39;, value.length);<br>    return;<br>  } <br>  if (Array.isArray(value)) {<br>    console.log(&#39;Array length is:&#39;, value.length);<br>    return;<br>  } <br>  console.log(&#39;Length is:&#39;, value.length);<br>}</pre><p>This function accepts any value that has a length: number property.</p><pre>logLength(&#39;Hello world!&#39;) // String length is: 12<br>logLength([&#39;Hello&#39;, &#39;world!&#39;]) // Array length is: 2</pre><p>String primitives, arrays, and any object with a length: number property are valid. TypeScript uses structural typing here—the value just needs to <em>have the right shape</em>, regardless of what it actually is.</p><h4>“How”: String Interface Example</h4><p>Similarly, the String interface describes the shape of a string value—it covers both string primitives and String objects:</p><pre>const stringPrimitive: String = &quot;Hello&quot;;<br>const stringObject: String = new String(&quot;world!&quot;);</pre><p>This tells TypeScript how the value can be used (methods like toUpperCase, charAt, etc.) but not what the value actually <em>is</em>.</p><h4>“What”: string Type Example</h4><p>By contrast, the string type describes <em>what</em> the value is: a primitive string. But because string extends the String interface, it also implicitly defines <em>how</em> the value can be used.</p><pre>const stringPrimitive: string = &quot;Hello&quot;;<br>const stringObject: string = new String(&quot;world!&quot;);<br>   // ^^^^^^^^^^^^^<br>   // Type &#39;String&#39; is not assignable to type &#39;string&#39;.</pre><p>Only actual string primitives are assignable to string, even though String instances have the same interface.</p><h3>Introducing the object type</h3><p>In TypeScript, the object type is meant to represent any non-primitive value.</p><blockquote>TypeScript did not have a type that represents the non-primitive type, i.e. any thing that is not number, string, boolean, symbol, null, or undefined — <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type"><em>www.typescriptlang.org</em></a></blockquote><h4>The Expected: Rejecting Primitives</h4><p>As expected, TypeScript rejects primitives where a non-primitive is required. For example, Object.create() expects an argument of type object:</p><pre>const stringValue = &#39;definitelyPrimitive&#39;;<br>Object.create(stringValue); <br>           // ^^^^^^^^^^^<br>           // Argument of type &#39;string&#39; is not assignable to<br>           // parameter of type &#39;object&#39;.</pre><h4>The Unexpected: Allowing Uncertainty</h4><p>However, if the value’s type <em>might</em> be an object, TypeScript allows it — even if that leads to a <a href="https://www.typescriptlang.org/play/?#code/MYewdgzgLgBArmYBTATlAhgSzAFQJ4AOSAXDAMpQrYDmMAvDAOShwA2AJgEJIDyARgCskwKIwDcAKH5CRAOmAok6KEgAUCZGiy5CSAJRiYAeiMxAoOQxQAWwKZWSCABoYgGXJLKdBAAWDmMpgoCFCYVkhAA">runtime error</a>.</p><pre><br>const uncertainType: String = &#39;couldBeObject&#39;;<br>Object.create(uncertainType); // ✅ compiles, ❌ crashes at runtime</pre><p>This is inconsistent. TypeScript usually forces you to narrow down uncertain types before using them. Consider:</p><pre>let figure: string | number;<br>Math.round(figure); <br>        // ^^^^^^<br>        // Type &#39;string&#39; is not assignable to type &#39;number&#39;.</pre><p>So on one hand, TypeScript prevents using a known primitive where an object is required. But on the other, it permits ambiguous types — even if they <em>might</em> be primitives — without narrowing. That breaks with TypeScript’s usual “narrow or error” principle.</p><h3>The Flaw of the object Type</h3><h4>object and string</h4><p>Let’s start with the part TypeScript gets right. When comparing object to string, we see expected behaviour:</p><ul><li>object does <strong>not</strong> extend string</li><li>string does <strong>not</strong> extend object</li><li>object &amp; string resolves to never</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIdlFOI6DshRnay4cVo0LQ.png" /><figcaption><em>intersection between string and object</em></figcaption></figure><p>This holds true <a href="https://www.typescriptlang.org/play/?#code/PTAEGcBcCcEsDsDmAoAxge3lCMGIKIAekApvACbgDyARgFYmqQBcOcSoJxZlo69jSKAD8oGAFcSoVgDMAhgBtwUgLyh5SkgG40mbPwZMipCuADKuJKwODO3U2zwix0SdPWLloNRuU6MWEJQ7IhUAG4k0ApyAA7UAkyswU4AZHwJQlwmvPAkEdDOvlKsEqoemjrIIKDw4gC2NJG6gTX1jdDGPPGGLK0NkXbZ4Ok9zqXuRd7lfs36GZ2mAHJtkdYZg1197WOuxdNlRf56QrX90OGR0XG0Payn22k2TBsOufmFnnvjPp+V1TTodAKEhyeCzIQAoEg+ALSg3QSsSHA0EvXhPISicayT5TQ7gkaCWHgABCgOR8DWoyymyR0J2bmxmlxv3xtNBFyisW6CNAbPgoEe62przyA1EkxKu2ZFWQVTANFgiAQkFZiuVRPhiV5avgmXsaPWmKljK8PxlATmPSJxJ1vXRqOGCqVuvpe0mZpmFohto5V25WqdyoFBOewpyooK4pxkrcHu0suq4AAng0gfjk6mFBqMkkUwCFA6QxiXAz9tLPcci0SzHmgZTbGHhhn866Jji40cWs2gb6uZret2C4Kqfrhm8xWWYwcWXLWgoFPjavPs7c5wXG0XWybp+bK+iict5-XQ6O11uyx3F+J573rjmz8OG6fx5HJyWdzNZ+IKCQZAgSOQ+LfuQv7-uQK48sBoG5OQhb2kapbuvsnaWoSo4AKo-n+MHHnqQygFB2EAeeSF4l6BFYWBt7+r0hFgcG9obi+HxMlO5bxkAA">for all primitive types</a>: they don’t overlap with object, which makes sense.</p><h4>object and { }</h4><p>Things get weird when we compare object with {}.</p><p>The {} type represents all non-nullish values—everything except null and undefined. So it includes both primitives <em>and</em> non-primitives.</p><p>So far, this is expected:</p><ul><li>object extends {} (since all objects are non-nullish)</li><li>object &amp; {} resolves to object</li></ul><p>But here’s <a href="https://www.typescriptlang.org/play/?#code/PQKgBA9gRgVgpgYwC5jgDyXAdgEwM5gDeAvmCMAFAIRZ4rTzICiG2+AcjewK4A2vASzwALAFyRYiFOky4CJMAH4wSAE7c4YcQDMAhrzyaAvCvVwA3BQqgipAGQTG0gI7d9BBlLKVqtFHVUBLABzFlkOLj5BEXEwAKDg1FY5WyVTDS0wPQNjdIswKho6OLUEsLY8AHlJZFj4kKTwjxqUZTUMnXdc7MNLX2L60OT8AEksTFVDZAEaOtKGmQqwAAoFB09kAEo09s1OnLATHvyrGwVFlI2UckK-MCxI-iFhcrkAZXng8XPhgkGdsyZY6HLJdcxgYDAJIABykcBwt2KDywPCeIle+GqTm+pAu+EcXjagP2hhBu3BkLA3Cw6FhyHhFCAA">the problem</a>:</p><ul><li>{} also extends object</li></ul><p>This is a contradiction. If object only includes non-primitives, and {} includes <em>primitives</em>, then allowing {} to extend object breaks the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hRfWHKeZXPKAUTz_kDmSg.png" /><figcaption>object and non-nullish paradox</figcaption></figure><h4>Broken Transitivity</h4><p>This leads to a failure in a core principle of TypeScript’s type system:</p><blockquote>If A extends B and B extends C, then A extends C.</blockquote><p>This should be true every time, right?</p><p>In reality:</p><ul><li>string does <strong>not</strong> extends object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swTTfD1S-4egPPYPdZpDsA.png" /><figcaption>string does <strong>not</strong> extends object</figcaption></figure><p>Yet:</p><ul><li>String extends object</li><li>string extends String</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8PzHuKSHwiETRdgWDSOKQ.png" /></figure><p>So transitivity breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfE32jJooA0b56NnR8Jy8A.png" /><figcaption>string doesn’t extend object, or does it?</figcaption></figure><h4>The Core Flaw</h4><p>This inconsistency is rooted in an implicit assumption in the type system:</p><blockquote>If it might not be a primitive, then it extends object.</blockquote><p>This logic causes TypeScript to treat some uncertain or overlapping types (like String, or {}) as object, even when it results in unsound behaviour.</p><h3>Why this flaw exists</h3><p>When TypeScript behaves unexpectedly, it’s often because it optimizes for the 99% use case. This flaw likely exists to keep things simple for most developers.</p><p>But this issue only appears in edge cases, like:</p><ul><li>Deliberately using the String interface instead of the string primitive (which TypeScript <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean">explicitly discourages</a>)</li><li>Designing structural types (e.g. { length: number }) that can be satisfied by primitives</li></ul><p>These scenarios are rare — but they’re valid.</p><p>Still, simplicity for the common case doesn’t justify inconsistency in the rare case. TypeScript could preserve predictable, sound behaviour <em>without</em> sacrificing usability for the majority.</p><h3>Finding a fix</h3><h4>Introducing Implicitly Non-Primitive Types</h4><p>As we’ve seen, the object type is intended to represent non-primitives. But we can infer non-primitiveness without using object explicitly.</p><p>Any structural type that <strong>no primitive</strong> satisfies — like { foo: &#39;bar&#39; }—is, by definition, non-primitive. This can be inferred automatically:</p><pre>function primitiveForbidden(arg: object) {}<br><br>primitiveForbidden({ foo: &quot;bar&quot; }); // ✅ non-primitive</pre><p>In practice, the object keyword would only be needed when the type is uncertain or intentionally generic.</p><h4>This Behavior Already Exists (Partially)</h4><p>This isn’t hypothetical — TypeScript’s control flow analysis <em>already</em> does something similar:</p><pre>let mightBeString: { length: number };<br><br>if(typeof mightBeString === &#39;string&#39;) {<br>  mightBeString; // inferred as string<br>}<br><br>let definitelyNotString: { foo: &#39;bar&#39; };<br><br>if(typeof definitelyNotString === &#39;string&#39;) {<br>  definitelyNotString; // inferred as never<br>}</pre><p>When TypeScript sees a shape that can’t possibly match a primitive, it narrows it out automatically. This is already a partial form of implicit non-primitive tagging.</p><p>Extending this inference more broadly could eliminate the need for object in most real-world use cases.</p><h4>Do We Need Explicit Non-Primitives?</h4><p>Would this shift require writing a lot of explicit &amp; object annotations?</p><p>Probably not.</p><p>In most cases, this explicit tagging would be inferred on its own:</p><pre>let stringish = { length: 10 }; // inferred as object &amp; { length: number }<br><br>stringish = &#39;test&#39;; // would now be invalid<br><br>if(typeof stringish === &#39;string&#39;) {<br>    // would now be infered as never<br>}</pre><p>For the remaining uncertain types, two approach are possible:</p><ul><li>Explicitly add &amp; object to disambiguate</li><li>Narrow types when needed</li></ul><p>For typical codebases, this change would affect almost nothing.</p><h3>The End of Branded Types</h3><p>The real disruption is a side effect: <strong>branded types would break</strong>.</p><p>Right now, branded types often rely on intersecting a primitive with a unique shape:</p><pre>type Id = string &amp; { __brand: &#39;id&#39; }</pre><p>With implicit non-primitiveness, this would now resolve to never—because { __brand: ... } would never match a primitive.</p><p>That would make code like this invalid:</p><pre>const id: Id = &#39;abc&#39; // Type &#39;&quot;abc&quot;&#39; is not assignable to type &#39;never&#39;</pre><p>This is significant. Branding is commonly used to distinguish structurally identical types — like IDs or properties from different entities. It prevents mistakes like this:</p><pre>type ProductId = number;<br><br>const getProductById = (id: ProductId) =&gt; {<br>  // Logic to retrieve product<br>}<br><br>type UserId = number;<br><br>const id: UserId = 1<br><br>getProductById(id) // No type error, but incorrect usage</pre><p>Libraries like <a href="https://github.com/kourge/ts-brand">ts-brand</a> or frameworks like <a href="https://effect.website/">Effect</a> rely on this pattern. Implicit non-primitives would break these techniques unless an alternative branding mechanism were introduced.</p><h3>Final thoughts</h3><p>This is not a new issue — multiple GitHub threads have discussed it, and it <a href="https://github.com/microsoft/TypeScript/issues/60582">continues to resurface</a>.</p><p>The problem tends to go unnoticed because TypeScript behaves correctly in most cases. But once you start digging into why object and {} exist separately—and why they extend each other—it becomes clear that there&#39;s an inconsistency at the core of the type system.</p><p>Introducing a compiler option like strictNonPrimitiveCheck could resolve this without breaking common usage. It would bring clarity to how object is meant to behave and eliminate subtle, unsound edge cases.</p><p>Links to experiments:</p><ul><li><a href="https://www.typescriptlang.org/play/?#code/PTAEGcBcCcEsDsDmAoAxge3lCMGIKIAekApvACbgDyARgFYmqQBcOcSoJxZlo69jSKAD8oGAFcSoVgDMAhgBtwUgLyh5SkgG40mbPwZMipCuADKuJKwODO3U2zwix0SdPWLloNRuU6MWEJQ7IhUAG4k0ApyAA7UAkyswU4AZHwJQlwmvPAkEdDOvlKsEqoemjrIIKDw4gC2NJG6gTX1jdDGPPGGLK0NkXbZ4Ok9zqXuRd7lfs36GZ2mAHJtkdYZg1197WOuxdNlRf56QrX90OGR0XG0Payn22k2TBsOufmFnnvjPp+V1TTodAKEhyeCzIQAoEg+ALSg3QSsSHA0EvXhPISicayT5TQ7gkaCWHgABCgOR8DWoyymyR0J2bmxmlxv3xtNBFyisW6CNAbPgoEe62przyA1EkxKu2ZFWQVTANFgiAQkFZiuVRPhiV5avgmXsaPWmKljK8PxlATmPSJxJ1vXRqOGCqVuvpe0mZpmFohto5V25WqdyoFBOewpyooK4pxkrcHu0suq4AAng0gfjk6mFBqMkkUwCFA6QxiXAz9tLPcci0SzHmgZTbGHhhn866Jji40cWs2gb6uZret2C4Kqfrhm8xWWYwcWXLWgoFPjavPs7c5wXG0XWybp+bK+iict5-XQ6O11uyx3F+J573rjmz8OG6fx5HJyWdzNZ+IKCQZAgSOQ+LfuQv7-uQK48sBoG5OQhb2kapbuvsnaWoSo4AKo-n+MHHnqQygFB2EAeeSF4l6BFYWBt7+r0hFgcG9obi+HxMlO5bxkAA">Primitives in relation to object</a></li><li><a href="https://www.typescriptlang.org/play/?#code/PQKgBA9gRgVgpgYwC5jgDyXAdgEwM5gDeAvmCMAFAIRZ4rTzICiG2+AcjewK4A2vASzwALAFyRYiFOky4CJMAH4wSAE7c4YcQDMAhrzyaAvCvVwA3BQqgipAGQTG0gI7d9BBlLKVqtFHVUBLABzFlkOLj5BEXEwAKDg1FY5WyVTDS0wPQNjdIswKho6OLUEsLY8AHlJZFj4kKTwjxqUZTUMnXdc7MNLX2L60OT8AEksTFVDZAEaOtKGmQqwAAoFB09kAEo09s1OnLATHvyrGwVFlI2UckK-MCxI-iFhcrkAZXng8XPhgkGdsyZY6HLJdcxgYDAJIABykcBwt2KDywPCeIle+GqTm+pAu+EcXjagP2hhBu3BkLA3Cw6FhyHhFCAA">object in relation to non-nullish</a></li></ul><h3>À propos d’ekino</h3><blockquote><em>Le groupe ekino accompagne les grands groupes et les start-up dans leur transformation depuis plus de 10 ans, en les aidant à imaginer et réaliser leurs services numériques et en déployant de nouvelles méthodologies au sein des équipes projets. Pionnier dans son approche holistique, ekino s’appuie sur la synergie de ses expertises pour construire des solutions pérennes et cohérentes.</em></blockquote><blockquote><em>Pour en savoir plus, rendez-vous sur notre site — </em><a href="https://www.ekino.fr/"><em>ekino.fr.</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc95b6c663f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ekino-france/typescript-object-doesnt-make-sense-fc95b6c663f9">TypeScript “object” doesn’t make sense</a> was originally published in <a href="https://medium.com/ekino-france">ekino-france</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liquid Glass in CSS (and SVG)]]></title>
            <link>https://medium.com/ekino-france/liquid-glass-in-css-and-svg-839985fcb88d?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/839985fcb88d</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 07:03:00 GMT</pubDate>
            <atom:updated>2025-07-16T07:03:00.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vcn3HHZvI8eovLq61hnc_A.png" /><figcaption>Background Picture: Aldrin near the lunar module (<a href="https://eol.jsc.nasa.gov/SearchPhotos/photo.pl?mission=AS11&amp;roll=40&amp;frame=5902">Apollo 11</a>)</figcaption></figure><h3>TL;DR</h3><p>Apple’s Liquid Glass design features complex refraction that distorts content beneath UI elements. While CSS backdrop-filter doesn’t natively support such effects, SVG filters can bridge the gap. Using &lt;feDisplacementMap&gt;, we can replicate similar results in Chromium-based browsers.</p><h3>What is Liquid Glass ?</h3><p>Liquid Glass is Apple’s new design language introduced in their next OS iteration (version 26), evolving from the simpler blur effects first seen in iOS 7.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjGztGfRujSE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjGztGfRujSE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjGztGfRujSE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd88f46c4ffd5789957003fcdd24694d/href">https://medium.com/media/bd88f46c4ffd5789957003fcdd24694d/href</a></iframe><p>Unlike simple blurs, Liquid Glass mimics real glass’s optical properties — most notably, <strong>refraction</strong>.</p><p>There are several variations of this effect depending on context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aU5VMLm3IQRAb4uSFZfq1Q.png" /><figcaption>Safari App — <a href="https://youtu.be/jGztGfRujSE?feature=shared&amp;t=143">Introducing Liquid Glass | Apple</a></figcaption></figure><p>Sometimes the element is fully transparent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ob48NFGJ1ldpO9KfBxuUug.png" /><figcaption>Text magnification — <a href="https://youtu.be/jGztGfRujSE?feature=shared&amp;t=94">Introducing Liquid Glass | Apple</a></figcaption></figure><p>Other times it blurs and distorts heavily the content beneath it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyXzskUbPq9z8_2Am3DYgQ.png" /><figcaption>Apple TV+ App —<a href="https://youtu.be/jGztGfRujSE?feature=shared&amp;t=133"> Introducing Liquid Glass | Apple</a></figcaption></figure><p>A constant feature, however, is that the element’s borders create a symmetrical distortion of the inner content beyond a certain threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEK4P2Yaz-G7gN6i6_Nx3g.png" /><figcaption>Answering a phone call —<a href="https://youtu.be/jGztGfRujSE?feature=shared&amp;t=121"> Introducing Liquid Glass | Apple</a></figcaption></figure><p>While Liquid Glass encompasses more than just border distortions, this article will focus primarily on that aspect.</p><h3>The CSS implementation</h3><p>CSS offers the backdrop-filter property, which lets you apply effects like blur or brightness to the content behind an element. These filters stack cumulatively, applied in sequence. A simple setup might look like this:</p><pre>.my-element {<br>    backdrop-filter: blur(10px) brightness(0.8);<br>}</pre><p>However, CSS lacks a native way to create distortion or refraction effects. To achieve those, we need to harness SVG filters. You can reference an SVG filter inside backdrop-filter by using a URL syntax like:</p><pre>backdrop-filter: url(https://medium.com/my-svg.svg#myfilter);</pre><blockquote><strong><em>Note:</em></strong><em> One limitation is that </em><em>backdrop-filter only affects content within the element’s boundaries. In Apple’s Liquid Glass presentation, some elements refract content beyond their borders—something we can’t replicate using </em><em>backdrop-filter alone.</em></blockquote><h3>The SVG implementation</h3><p>The SVG specification lets you define filters that produce complex visual effects on shapes and symbols. Although SVG is a vector format, filters operate in a rasterized context — converting vector graphics into pixel-based images before applying effects. Filters are composed of building blocks called <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Element#filter_primitive_elements">filter primitives</a>, which fall into three main categories:</p><ul><li><strong>Modifiers</strong> — transform an existing graphic (e.g., &lt;feGaussianBlur /&gt;)</li><li><strong>Sources</strong> — generate new graphics (e.g., &lt;feTurbulence /&gt;)</li><li><strong>Combiners</strong> — merge multiple graphics to create a new output</li></ul><p>The primitive we need for refraction effects belongs to this last category.</p><h4>&lt;feDisplacementMap /&gt;</h4><p>The displacement filter combines two inputs to produce the distorted output. The first input, usually SourceGraphic, is the original visual we want to distort. The second input is the displacement map, which controls how each pixel of the original image is shifted. Each pixel’s offset is determined by reading the corresponding pixel in the displacement map.</p><p>We can generate a random displacement map using &lt;feTurbulence /&gt;, which creates chaotic distortion patterns.</p><pre>&lt;filter id=&quot;turbulence-displacement&quot;<br>        x=&quot;0&quot; y=&quot;0&quot;<br>        width=&quot;100%&quot; height=&quot;100%&quot;&gt;<br>   &lt;!-- Source --&gt;<br>   &lt;feTurbulence type=&quot;turbulence&quot;<br>                 baseFrequency=&quot;0.05&quot;<br>                 numOctaves=&quot;2&quot;<br>                 result=&quot;noise&quot; /&gt;<br>   &lt;!-- Combiner --&gt;<br>   &lt;feDisplacementMap in=&quot;SourceGraphic&quot;<br>                      in2=&quot;noise&quot;<br>                      scale=&quot;20&quot;<br>                      xChannelSelector=&quot;R&quot;<br>                      yChannelSelector=&quot;G&quot; /&gt;<br>&lt;/filter&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsIcTnFIq3X7HKyZaan9sw.png" /><figcaption>Turbulence-based distortions with varying baseFrequency.</figcaption></figure><p>However, to achieve precise border distortions like in Liquid Glass, we need a dedicated displacement map image. This is where &lt;feImage /&gt; comes in: it allows us to use external graphics as filter inputs.</p><pre>&lt;filter id=&quot;image-displacement&quot;<br>        x=&quot;0&quot; y=&quot;0&quot;<br>        width=&quot;100%&quot; height=&quot;100%&quot;&gt;<br>   &lt;!-- Source --&gt;<br>   &lt;feImage xlink:href=&quot;displacement-map.svg&quot;<br>            result=&quot;dispMap&quot; /&gt;<br>   &lt;!-- Combiner --&gt;<br>   &lt;feDisplacementMap in=&quot;SourceGraphic&quot;<br>                      in2=&quot;dispMap&quot;<br>                      scale=&quot;30&quot;<br>                      xChannelSelector=&quot;R&quot;<br>                      yChannelSelector=&quot;G&quot; /&gt;<br>&lt;/filter&gt;</pre><p>While &lt;feImage /&gt; can load raster images like PNGs, we’ll use a second SVG file to generate the displacement map. Creating it as SVG lets us precisely match the size and border radius of the target element, which is crucial for accurate distortion. A “generic” map wouldn’t scale correctly across varying element dimensions, leading to misaligned or inconsistent refraction. And although the source is vector-based, keep in mind that all filters—including displacement—operate on a rasterized version, so there’s no inherent quality gain from using SVG.</p><h3>Creating the displacement map</h3><p>The xChannelSelector and yChannelSelector attributes determine which color channels (R, G, B, or A) drive the displacement along the horizontal and vertical axes. The selected channel provides a value between 0 and 255 for each pixel, which gets mapped like this:</p><ul><li>00 → full negative offset (–1)</li><li>80 (128) → no displacement (0)</li><li>FF (255) → full positive offset (+1)</li></ul><p>These normalized values are then scaled using the scale attribute to produce the final displacement per axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNMj0Q-0ajqKMaJPTLFw3w.png" /></figure><p>Using a solid gray image results in no displacement. The red channel (#<strong>80</strong>8080) is used for the <em>x-axis</em> and the green channel (#80<strong>80</strong>80) is used for the <em>y-axis</em>. The blue channel value is ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Q868HIEJHHcBo2d_HNbiQ.png" /></figure><p>In contrast, using a solid red image (#FF0000) shifts pixels to the left on the <em>x-axis</em> and to the bottom on the <em>y-axis</em>. When displaced pixels fall outside the graphic boundaries, their values are sampled from a mirrored version of the original image to avoid harsh edges.</p><p>What about gradients? Here I created a displacement map by layering two gradients, one for each axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHaHHlY5uiSClhnub3xIUg.png" /></figure><p>According to the scale value, the resulting picture is either zoomed in, zoomed out or even inverted.</p><p>Linear gradients across the whole axis don’t produce distortion; they only scale the image uniformly. Real distortion requires irregular gradients.</p><blockquote><strong><em>Note:</em></strong><em> In the image above, the zoom effect appears slightly skewed. Displacement rendering seems a bit off on macOS but looks correct on Windows. Fortunately, the difference is subtle and barely noticeable in the final result.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxGwhQ83KUvaelMV8xDJOQ.png" /></figure><p>The above example gets us closer to Liquid Glass’s effect but misses the subtle border distortions and rounded corners. To fix this, I combined the linear gradient displacement map with a solid gray mask matching the element’s shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaNLbPxWfusmsESAjxVEJw.png" /></figure><p>Blurring this mask creates a smooth transition between displaced and non-displaced areas, mimicking the natural bending of edges.</p><h3>Result</h3><p>The result is an approximate refraction effect that closely mimics Apple’s Liquid Glass aesthetic — at least visually. We can also push the idea further by simulating <a href="https://en.wikipedia.org/wiki/Chromatic_aberration">chromatic aberration</a> which is a very common behaviour of real glass. You can see the result in motion on the following sandbox:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fg3mwqp%3Fview%3Dpreview%26hidenavigation%3D1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fg3mwqp&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fg3mwqp%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/06cb8d52505e6180e5cfef4fc8e7d17b/href">https://medium.com/media/06cb8d52505e6180e5cfef4fc8e7d17b/href</a></iframe><p>That said, the rendering isn’t as refined. One major limitation is the lack of super-sampling in SVG displacement filters, which leads to a pixelated look. This can be softened slightly with blur, but it’s not a perfect fix.</p><h3>Constraints</h3><p>This proof of concept reveals several limitations when simulating refraction with SVG. Unlike Apple’s Liquid Glass, which works on arbitrary shapes — including text and icons — this approach currently only supports fixed-size rounded rectangles and circles.</p><p>Compatibility is another major constraint: the technique only works reliably in Chromium-based browsers. While the displacement effect itself should be <a href="https://caniuse.com/mdn-api_svgfedisplacementmapelement">supported across most browsers</a>, combining it with backdrop-filter doesn&#39;t consistently work outside of Chromium.</p><p>Finally, ensuring the readability of the element’s content against unpredictable backgrounds remains a challenge, potentially introducing accessibility issues.</p><blockquote><strong><em>About computation costs:</em></strong><em> While Apple hints that Liquid Glass leverages modern hardware, there’s little to suggest it couldn’t run on much older chips — possibly even the A6. Blur filters typically sample and average multiple neighboring pixels per output pixel, making them relatively heavy. By comparison, displacement filters usually perform a single pixel lookup based on a coordinate offset, which is significantly cheaper. Given that iPhones have handled real-time blur since iOS 7, it’s reasonable to assume that a displacement effect like this was technically feasible over a decade ago.</em></blockquote><h3>Final Thoughts</h3><p>Liquid Glass introduces a type of refraction effect largely unseen in UI design, and while SVG’s &lt;feDisplacementMap&gt; lets us approximate it on the web, the approach remains limited by shape constraints and inconsistent browser support. The CSS Houdini API, which can extend the rendering pipeline, offers a promising way to create these effects natively and without shape restrictions. However, due to current browser compatibility issues, any implementation remains experimental and isn’t production-ready. Still, Houdini feels like an interesting playground I’m curious to explore soon.</p><p>If you found this experiment interesting, you might also enjoy our more technical deep dives — check out other articles from <a href="https://www.ekino.fr/">ekino</a> on <a href="https://medium.com/ekino-france">Medium</a>, and follow us on <a href="https://www.linkedin.com/company/ekino">LinkedIn</a> to stay updated on new posts and projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=839985fcb88d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ekino-france/liquid-glass-in-css-and-svg-839985fcb88d">Liquid Glass in CSS (and SVG)</a> was originally published in <a href="https://medium.com/ekino-france">ekino-france</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript: The problem with function overloads]]></title>
            <link>https://javascript.plainenglish.io/typescript-the-problem-with-function-overloads-017f8bd2c78d?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/017f8bd2c78d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 04:16:29 GMT</pubDate>
            <atom:updated>2024-07-06T18:30:34.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdfxNXrHT5tmHs3QsQ0ciA.png" /><figcaption>Background <a href="https://unsplash.com/photos/blue-white-and-red-abstract-painting-NTYYL9Eb9y8">image</a> by <a href="https://unsplash.com/@pawel_czerwinski">Pawel Czerwinski</a></figcaption></figure><p><strong>TL;DR:</strong> function overloads are unsafe, and you probably don’t need polymorphic functions anyway.</p><p>In a previous article, <a href="https://medium.com/@adrgautier/zod-why-youre-using-typescript-wrong-b0c1583df089"><em>Why you’re using TypeScript wrong</em></a><em>, </em>I explained that TypeScript is designed to improve productivity at the expense of safety. In this article, we will see how the function overloading pattern in TypeScript is inherently unsafe. We will also explore alternatives to this approach and their potential limitations.</p><h3>What is function overloading ?</h3><p>Function overloading is the approach of implementing Ad Hoc polymorphism (also called “polymorphic functions”) in TypeScript. The idea is to declare a function that behave differently according to its input.</p><pre>/**<br> * Create a random number.<br> */<br>function random(mode: &quot;number&quot;): number;<br><br>/**<br> * Create a random string.<br> */<br>function random(mode: &quot;string&quot;): string;</pre><p>Function overloading works by declaring the overload signatures first (snippet above), followed with the actual function implementation (snippet below):</p><pre>function random(mode: &quot;string&quot; | &quot;number&quot;): string | number {<br>  if(mode === &quot;string&quot;) {<br>    return uuidv4();<br>  }<br>  return Math.random();<br>}</pre><p>When calling the function, the return type is properly inferred according to the input value:</p><pre>const randomString: string = random(&quot;string&quot;);<br><br>const randomNumber: number = random(&quot;number&quot;);</pre><blockquote><em>If you want to learn more on the subject of polymorphism in TypeScript please consider taking a look at my previous article: </em><a href="https://medium.com/@adrgautier/every-polymorphism-in-typescript-8938bea948be"><em>Every polymorphism in TypeScript</em></a><em>.</em></blockquote><h3>What you need to know before using it</h3><h4>It doesn’t handle uncertain parameters</h4><p>One goal of TypeScript is to describe <strong>uncertainty</strong>. Using a simple | “pipe”, you can declare that an object can be either A or B.</p><pre>type StringOrNumber = string | number;</pre><p>Uncertainty is omnipresent in our code, and it’s very common to call a function with an uncertain value. The problem is that TypeScript needs to be certain on build-time, which overload signature must be called for the given input. Using the random function previously declared:</p><pre>random(mode as &quot;string&quot; | &quot;number&quot;); // This won&#39;t build.</pre><p>We know that, in all cases, the same function will be called at runtime, but TypeScript doesn’t allow for uncertainty here.</p><blockquote>… TypeScript can only resolve a function call to a single overload.<em> — </em><a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads"><em>TypeScript Documentation</em></a></blockquote><p>I believe this limitation is here to mimic how function overloading works in other languages, but I don’t understand how relevant it is in TypeScript. I would rather expect the uncertainty to “propagate” naturally to the return type.</p><h4>The declarations can lie</h4><p>With function overloads, the overload signatures constraint how the function is used, but not how it is implemented. Let’s take the following example :</p><pre>function random(mode: &quot;string&quot;): string;<br><br>function random(mode: &quot;number&quot;): number;<br><br>function random(mode: unknown): unknown {<br>  return Math.random();<br>}</pre><p>The type checking actually works the other way around: an overload signature is valid if its parameters and return type are a <strong>subset</strong> of those of the implementation function. Since everything is a subset of unknown, we are free to declare just about any overload signature in the above example.</p><p>In short, TypeScript trusts the developer to implement a function that makes sense with its overload signatures.</p><h3>Alternative 1: conditional return type</h3><p>The main goal of the function overloads is to condition the return type according to the input parameters. We can achieve a similar behavior with the <a href="https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#handbook-content">conditional type</a> syntax as follows:</p><pre>function random&lt;TMode extends &quot;string&quot; | &quot;number&quot;&gt;(<br>  mode: TMode<br>): TMode extends &quot;string&quot; ? string : number {<br>  if (mode === &quot;string&quot;) {<br>    return uuidv4();<br>  }<br>  return Math.random();<br>}</pre><p>With the above syntax, we assert that:</p><ul><li>the mode argument is either &quot;string&quot; or &quot;number&quot;</li><li>if the mode is &quot;string&quot; the return type is string</li><li>else the return type is number</li></ul><p>Similarly to function overloads, the return type is properly inferred according to the input value:</p><pre>const randomString: string = random(&quot;string&quot;);<br><br>const randomNumber: number = random(&quot;number&quot;);</pre><h4>It handles uncertain parameters…</h4><p>Unlike function overloads, <strong>uncertain input values are allowed</strong> and propagates to the returned type as expected:</p><pre>const randomValue: string | number = random(mode as &quot;string&quot; | &quot;number&quot;);</pre><h4>…but fails to constraint implementation</h4><p>The good news sadly ends here. In order to satisfy the conditional return type, we actually need to introduce the type any:</p><pre>function random&lt;TMode extends &quot;string&quot; | &quot;number&quot;&gt;(<br>  mode: TMode<br>): TMode extends &quot;string&quot; ? string : number {<br>  if (mode === &quot;string&quot;) {<br>    return uuidv4() as any;<br>  }<br>  return Math.random() as any;<br>}</pre><p>TypeScript is <strong>not able to infer</strong> when a string must be returned or when a number must be returned. Worse, neither string nor numberis assignable to the conditional return type. The cleanest approach I found is to use an alias like this:</p><pre>type Return&lt;TMode extends &quot;string&quot; | &quot;number&quot;&gt; = TMode extends &quot;string&quot;<br>  ? string<br>  : number;<br><br>function random&lt;TMode extends &quot;string&quot; | &quot;number&quot;&gt;(<br>  mode: TMode<br>): Return&lt;TMode&gt; {<br>  if (mode === &quot;string&quot;) {<br>    return uuidv4() as Return&lt;TMode&gt;;<br>  }<br>  return Math.random() as Return&lt;TMode&gt;;<br>}</pre><p>But even in that case, it won&#39;t prevent to return a string instead of a number, and the other way around.</p><blockquote><em>Why </em><em>TMode is not narrowed down with the </em><em>mode === &quot;string&quot; condition? This is because we narrow the type </em><strong><em>associated to</em></strong><em> an object, not the type (</em><a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases"><em>alias</em></a><em>) itself.</em></blockquote><h3>Alternative 2: Implementing a library</h3><p>Unsatisfied with the conditional return type approach, I decided to work on a library that would help me create <strong>type-safe polymorphic functions</strong> in TypeScript.</p><blockquote>Introducing…</blockquote><figure><img alt="fffunction" src="https://cdn-images-1.medium.com/max/1024/1*FXX2ZP6MASb2Vi5t9kRaoA.png" /></figure><p>This tool provides a simple and concise API to declare the function signatures and the implementation. Here is an example with the random function:</p><pre>const random = fffunction<br>    .f&lt;&quot;number&quot;, number&gt;()<br>    .f&lt;&quot;string&quot;, string&gt;()<br>    .f(function ({ input, output }) {<br>      if (input === &quot;number&quot;) {<br>        return output(Math.random());<br>      }<br>      return output(uuidv4());<br>    });</pre><p>Each signature declaration define the input and the output types:</p><pre>fffunction<br>   .f&lt;&quot;string&quot;, string&gt;()<br>   .f&lt;&quot;number&quot;, number&gt;()</pre><p>Then the actual function is implemented with the help of the input property and the output method:</p><pre>/*...*/<br>   .f(function implementation({ input, output }) { /*...*/ })</pre><p>Using the output function, we make sure (on build-time) that the given value does match the expected return type from the signature. The compiler will throw an error if the types don’t match:</p><pre>return output(Math.random());<br>              ^^^^^^^^^^^^^ <br>              // Type &#39;number&#39; does not satisfy the constraint &#39;string&#39;</pre><blockquote><em>You can find more information about </em><strong><em>fffunction</em></strong><em> </em><a href="https://www.npmjs.com/package/fffunction"><em>in its readme</em></a><em>.</em></blockquote><h3>You don’t need polymorphic functions</h3><p>Let’s face it, you probably don’t need polymorphic functions.</p><p>Virtually all the problems I’ve explained throughout this article can be solved doing one simple thing: <strong>use a dedicated function</strong> for each signature. That means we deal with the uncertainty using a condition outside the function. We narrow first, then call the corresponding behavior:</p><pre>let uniqueId;<br>if(highComplexity === true) {<br>  uniqueId = randomString();<br>} else {<br>  uniqueId = randomNumber();<br>}</pre><p>Factorizing your code like this should work 99% of the time. But if somehow you cannot divide your logic into distinct functions, you now know the limits and risks of function overloading in TypeScript and the possible alternatives.</p><p>If you want to discover other unsafe patterns in TypeScript, I strongly recommend <a href="https://portal.gitnation.org/contents/the-lies-we-tell-ourselves-using-typescript">the talk by Stefan Baumgartner</a> at TS Congress 2023 (which inspired me to write this article).</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=017f8bd2c78d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/typescript-the-problem-with-function-overloads-017f8bd2c78d">TypeScript: The problem with function overloads</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zod: The truth about data validation]]></title>
            <link>https://medium.com/ekino-france/zod-the-truth-about-data-validation-7de964f581fd?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de964f581fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-validation]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Fri, 24 May 2024 09:50:09 GMT</pubDate>
            <atom:updated>2024-06-24T15:53:44.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyfkDAuX75NDfziqb0G7yQ.png" /><figcaption>Background picture by <a href="https://unsplash.com/photos/blue-abstract-wallpaper-PfiCEBmKTqY">Ash Edmonds</a></figcaption></figure><p><strong>TL;DR:</strong> Validating data is not about types, it is about determining when and where the app encounters failures.</p><p>This article serves as a sequel to <a href="https://medium.com/ekino-france/zod-why-youre-using-typescript-wrong-b0c1583df089">my previous article</a> about Zod. Here, I’ll shift away from TypeScript and explore what is the principle behind data validation and what we should expect from it. This article’s focus is not Zod, but it should answer some questions raised in comments to my previous article.</p><h3>1. <em>“Never trust the backend”</em></h3><p>While it might come across as a provocative joke, there is definitely a bit of truth in that quote.</p><p>Some developers shared to me their experience utilizing the <strong>types generated from the API</strong> itself. I firmly believe this is a good starting point to avoid most of the data related issues and bugs.</p><p>However, you should keep in mind that, if the backend API is being developed <strong>concurrently</strong> to the frontend :</p><ul><li>you may use an outdated version of the types</li><li>backend data migration can fail, resulting in a mismatch between the data and the ORM structure</li></ul><p>Both scenario can indeed lead to runtime issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDlB3jTyqm-aB8lFUeqJjg.png" /><figcaption>Oops, that was supposed to be a description.</figcaption></figure><blockquote>Data validation can ensure, on <strong>runtime</strong>, the validity of any given object with a defined schema.</blockquote><p>Having good types is not sufficient. There is always a possibility that the data doesn’t conform to the expected format. Hence, the necessity for data validation.</p><h3>2. It is not about types</h3><p>In my previous article, I demonstrated, with a TypeScript flaw, why it is essential to validate external data with Zod (or any validation library). But external data validation remains important whether you use TypeScript or not. In fact, TypeScript compile-time “validation” may have caused us to overlook the risks at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2d0q73hPAlLpbnQY2yIvmg.png" /></figure><p>In the JavaScript times (before TypeScript), web developers used to implement basic protection by mapping the object structure as follows :</p><pre>function parseUser(data) {<br>  try {<br>    return {<br>      name: data.name,<br>      email: data.email,<br>      address: {<br>        street: data.address.street,<br>      }<br>    }<br>  } catch {<br>    throw new Error(&#39;Invalid data&#39;);<br>  }<br>}</pre><p>This kind of function was used directly after fetching the data.</p><p>In a TypeScript code, data would be already typed and parseUser would output the exact same type. As a result, this entire snippet would seem useless.</p><p>While rudimentary, this piece of code is far from useless : It executes operations prone to crashing within a “controlled environment”. By retrieving all the data individually, we ensure that the expected structure is fulfilled. If any of the parameter is missing, it will fail. A great deal of crashes is thus avoided throughout the application, although there remains a chance to perform an invalid operation on a parameter itself.</p><p>This primitive example of data validation introduces an important principle : <strong>failing as soon as possible</strong>.</p><h3>3. With validation comes errors</h3><p>One misconception of data validation, is that it can reduce errors. The accurate perspective is that it can prevent <strong>crashes</strong>. In fact, properly executed data validation is likely to throw or display more errors.</p><h4>No more silent bugs</h4><p>Sometimes, the application does not crash, but runs in a “degraded” mode. Some features will not work quite as intended, or the data will not be displayed properly.</p><p>With data validation, silent bugs becomes errors. As soon as the data is fetched, the application will ascertain whether the requirements are met for all the dependent screens to display and function properly.</p><p>If the requirements are not met, then the application can display a fallback or an error screen. Displaying the error immediately can prevent deceptive user experiences, such as forms leading to unexpected errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*wXnS61RIasYltQqFt6ueZg.png" /><figcaption>You don’t want to see that after a long form.</figcaption></figure><p>It is also possible to design a screen with a “degraded” variant, which can work with only a partial API response. Data validation enables better fallbacks for each situation.</p><h4>Better error tracking</h4><p>Along with enhancing UX, data validation also improves developer experience by streamlining the debugging process. Validating data just after fetching allows to gather two of the most error-prone operations in a single point in time and “in code”.</p><p>If these errors are properly tracked, labeled and logged in a monitoring service, a significant amount of time should be saved in investigations. We never need to ask ourselves again: Is it caused by data ?</p><h3>4. “Never trust the backend”</h3><p><em>(No, this is not an attempt at a running gag.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoKOfyLhli61kcl5vRq3WQ.png" /></figure><p><a href="https://ajv.js.org/">Ajv</a> has been suggested in comments on my previous article for data validation. It is real validation, which means all the benefits I exposed earlier. But, in my experience, this solution has a drawback :</p><p>There is a chance that the OpenAPI schemas <strong>do not match perfectly the actual implementation</strong> of the API. Maybe I&#39;ve had bad luck, with OpenAPI schemas, but I would not always rely on those (depending on how they have been generated) to perform data validation.</p><p>Also, OpenAPI and Ajv are not ideal with TypeScript application. It requires updating the type declarations along with the OpenAPI schemas. They can be generated automatically, but I don’t like this approach. Instead of <strong>declaring the API structure twice</strong>, I prefer to think of the validation step with another perspective.</p><p>The data validation schemas must define <strong>the requirements</strong> of the frontend application. Of course, these requirements are not solely determined by the frontend. They can be the result of a concerted work between the backend and the frontend. Or, taking a public API as an example, the requirements will be the intersection of the frontend needs and the API implementation.</p><p>In other words, we should <strong>only validate</strong> what the application <strong>really needs</strong>.</p><h3>Summary</h3><p>Good type declarations are not enough, our applications must be prepared for unexpected external data. Data validation allows preventing crashes, and enables finer handling of errors. If tracked properly, this can improve debugging efficiency. It may be tempting to rely on the OpenAPI provided by the backend, but you should only validate what the application needs. For all these reasons, I suggest writing your own validation schemas with tools like Zod, keeping in mind the application’s requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de964f581fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ekino-france/zod-the-truth-about-data-validation-7de964f581fd">Zod: The truth about data validation</a> was originally published in <a href="https://medium.com/ekino-france">ekino-france</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every polymorphism in TypeScript]]></title>
            <link>https://medium.com/@adrgautier/every-polymorphism-in-typescript-8938bea948be?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/8938bea948be</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 08:15:05 GMT</pubDate>
            <atom:updated>2024-02-20T21:29:26.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmrurQ48U0JFZ83sm2GKJQ.png" /><figcaption>Background picture by <a href="https://unsplash.com/photos/a-close-up-of-a-colorful-abstract-background-7ojoj0-ac40">Milad Fakurian</a></figcaption></figure><p>While writing about function overloading in TypeScript, I stumbled upon the existence of <strong>three major types</strong> of <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">polymorphism in programming theory</a>. In this article, I’ll introduce these three types of polymorphism in TypeScript using <strong>simple examples</strong>.</p><h3>Parametric polymorphism</h3><p>If you use <a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#generic-functions">generic functions</a> in TypeScript, you may have used this pattern without knowing. Consider the following function of dubious utility:</p><pre>function arrayEntries&lt;T&gt;(items: Array&lt;T&gt;): Array&lt;[number, T]&gt; {<br>  return items.map((item, index) =&gt; [index, item]);<br>}</pre><p>The arrayEntries function is called “generic” because its input type is not known during declaration. When called, it will infer the type of the returned data.</p><pre>const entries = arrayEntries([&#39;one&#39;, &#39;two&#39;]); // [[0, &#39;one&#39;], [1, &#39;two&#39;]]</pre><p>In the above example, the constant entries will receive the type Array&lt;[number, string]&gt; according to the string items in argument.</p><p>“Generic functions” is just another name of <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametrically polymorphic</a> functions. Consequently, I believe generic types, like Array&lt;T&gt;, are also a form of parametric polymorphism, but don’t take my word for it.</p><h3>Subtype polymorphism</h3><p>This one is maybe less common in TypeScript, because it relies on classes:</p><pre>interface Pet {<br>  speak: () =&gt; void;<br>}<br><br>class Dog implements Pet {<br>  speak() {<br>    return &#39;woof woof!&#39;;<br>  }<br>}<br><br>class Cat implements Pet {<br>  speak() {<br>    return &#39;meow!&#39;;<br>  }<br>}</pre><p>In this example, both Dog and Cat are subtypes of Pet. We can create a listen function that accepts any subtypes of Pet:</p><pre>function listen(pet: Pet): void {<br>  console.log(pet.speak());<br>}</pre><p>This is called subtype polymorphism, as the speak method is available for any class that is a subtype of Pet, and its behavior can be unique to each class.</p><h3>Ad hoc polymorphism</h3><p>This is what I call “polymorphic functions”. Or rather, <a href="https://en.wikipedia.org/wiki/Ad_hoc_polymorphism">Ad hoc</a> is the term used by Christopher Strachey to classify this concept also known as <strong>function overloading</strong>.</p><p>Ad hoc polymorphism differs from parametric and subtypes polymorphism in that <strong>its behavior depends</strong> on its <strong>arguments</strong>. That means a <strong>specific implementation </strong>will be called according to the <strong>arguments’ type</strong>.</p><h4>Function overloading in C++</h4><p>The following C++ example, taken <a href="https://en.wikipedia.org/wiki/Function_overloading">from Wikipedia,</a> illustrates the coexistence of <strong>different implementations</strong> (and therefore <strong>different behaviors</strong>) for the same Volume function:</p><pre>int Volume(int s) {  // Volume of a cube.<br>  return s * s * s;<br>}<br><br>double Volume(double r, int h) {  // Volume of a cylinder.<br>  return 3.1415926 * r * r * static_cast&lt;double&gt;(h);<br>}<br><br>long Volume(long l, int b, int h) {  // Volume of a cuboid.<br>  return l * b * h;<br>}<br><br>int main() {<br>  std::cout &lt;&lt; Volume(10);<br>  std::cout &lt;&lt; Volume(2.5, 8);<br>  std::cout &lt;&lt; Volume(100l, 75, 15);<br>}</pre><h4>Function overloading in TypeScript</h4><p>In TypeScript, <a href="https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads">the approach</a> is a little bit different. Using the same example, we will start by writing one declaration (also called overload signature) for each behavior of the Volume function. I usually include a <a href="https://jsdoc.app/">JSDoc</a> comment with each declaration:</p><pre>/**<br> * Calculates the volume of a cube.<br> * @param {number} s - The length of the side of the cube.<br> * @returns {number} The volume of the cube.<br> */<br>function Volume(s: number): number;<br><br>/**<br> * Calculates the volume of a cylinder.<br> * @param {number} r - The radius of the cylinder&#39;s base.<br> * @param {number} h - The height of the cylinder.<br> * @returns {number} The volume of the cylinder.<br> */<br>function Volume(r: number, h: number): number;<br><br>/**<br> * Calculates the volume of a cuboid.<br> * @param {number} l - The length of the cuboid.<br> * @param {number} w - The width of the cuboid.<br> * @param {number} h - The height of the cuboid.<br> * @returns {number} The volume of the cuboid.<br> */<br>function Volume(l: number, h: number, b: number): number;</pre><p>Then we declare the actual implementation of the function:</p><pre>function Volume(d: number, h?: number, b?: number): number {<br>  if (h !== undefined &amp;&amp; b !== undefined) {<br>    return d * h * b;<br>  }<br>  if (h !== undefined) {<br>    return Math.PI * d * d * h;<br>  }<br>  return d * d * d;<br>}</pre><p>Unlike in C++, a <strong>single implementation</strong> is responsible for the <strong>different behaviors</strong> of the Volume function. Here, it is the if statements that conditions the behavior of the function, depending on the number of arguments supplied.</p><pre>console.log(Volume(10)); // Logs the volume of a cube.<br>console.log(Volume(2.5, 8)); // Logs the volume of a cylinder.<br>console.log(Volume(100, 75, 15)); // Logs the volume of a cuboid.</pre><h4>Polymorphisn’t</h4><p>With this example, we saw that a <strong>single implementation</strong> is used in conjunction with <strong>multiple declarations</strong>. This is very different from other languages, where each behavior has its own implementation. So can it really be called ad hoc polymorphism ?</p><p>While I can’t give a definitive answer to this question, I can highlight <strong>two advantages</strong> of using the function overloading approach with TypeScript.</p><p>In the previous example, the function overloading <strong>constraints how to use</strong> the Volume function. It is not possible to call the function like this:</p><pre>Volume(100, undefined, 15); // this won&#39;t build</pre><p>This would be possible with the function implementation alone, but the <strong>overload signatures</strong> prevent it. Also, thanks to the JSDoc comments, every way of using the function is clearly indicated by your IDE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQf_IwmF-t2jVQez3EzLuQ.png" /><figcaption>Example of the suggestions provided by the IDE</figcaption></figure><p>Regardless of how function overloading is implemented in TypeScript, I think it can improve code quality and avoid errors.</p><h3>Summary</h3><p>We’ve seen how parametric polymorphism, subtype polymorphism and ad hoc polymorphism are implemented in TypeScript and how function overloading differs from other programming languages. In my next article, I’ll explore in more detail the limitations of function overloading in TypeScript and some alternative solutions we can find to implement polymorphic functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8938bea948be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zod: Why you’re using Typescript wrong]]></title>
            <link>https://medium.com/ekino-france/zod-why-youre-using-typescript-wrong-b0c1583df089?source=rss-c04ba6407220------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c1583df089</guid>
            <category><![CDATA[data-validation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[zod]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Adrien Gautier]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 09:43:05 GMT</pubDate>
            <atom:updated>2024-06-24T15:50:15.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zod: Why you’re using TypeScript wrong</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yWoPL8XL-LPj16zCbUOhw.png" /><figcaption>Photo by <a href="https://unsplash.com/@badashphotos?utm_source=medium&amp;utm_medium=referral">Ash Edmonds</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>TL;DR:</strong> External data must be validated on runtime.</p><p>If you have some experience in web development, you have inevitably encountered runtime errors when working with external data coming from an API. Working with TypeScript helps to significantly reduce these errors by reminding the structure and type of any data, across the entire application. However, while TypeScript is good at preventing impossible operations on data <strong>known</strong> during compilation, it can be too permissive regarding <strong>external</strong> (in other words, <strong>unknown</strong>) data.</p><p>In this article, I will explain why TypeScript allows you to write code that can fail on runtime and how Zod can prevent these data-related errors.</p><h3>The goal of TypeScript</h3><p>As I said in the introduction, the idea behind TypeScript is to track the structure and type of any data across the entire code. This not only helps to provide autocompletion in the IDE, but it also prevents invalid operations that would cause errors during runtime. In theory, every possible runtime error can be predicted and identified during TypeScript <strong>compilation</strong>. But this is not the case.</p><h4>Is TypeScript missing its goal?</h4><p>In reality, TypeScript&#39;s primary objective is to improve productivity. This means that TypeScript will always chose productivity over “safety”.</p><p>A good demonstration of this is the type any. It exists, yet it’s widely accepted that we shouldn’t use it. However, not writing a single any in our code doesn&#39;t mean our application is immune from runtime errors. Take a look at the following snippet :</p><pre>const obviouslyAnArticle: Article = JSON.parse(input); // input is a string</pre><p>Because JSON.parse return type is any, it can be associated with a variable <strong>explicitly typed</strong> (as Articlein this example). Without writing any ourselves, we are telling TypeScript to ignore <strong>the runtime probability</strong> where the parsed content does not satisfy the type Article.</p><blockquote><em>We have to keep in mind that </em><em>any is often used in external definition files (</em><a href="https://github.com/microsoft/TypeScript/issues/26188"><em>and it doesn&#39;t look like this is going to change</em></a><em>) which means we must be even more careful.</em></blockquote><h4>unknown and assertions</h4><p>If unknown was used instead of any the above snippet would not be possible. We would be required to write explicit <a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions">assertions</a> using the as keyword :</p><pre>const shouldBeAnArticle = JSON.parse(input) as Article;</pre><p>With this syntax, we explicitly tell TypeScript to lower its guard. It is still bad, but no longer hidden!</p><h4><strong>Type narrowing </strong>expressions</h4><p>Instead of relying on unsafe type assertions, we can use <strong>type narrowing </strong>expressions.</p><blockquote>“the process of refining types to more specific types than declared is called narrowing”<em> — </em><a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html"><em>TypeScript documentation</em></a></blockquote><p>For example, the typeof operator (provided by JavaScript) can determine an object’s type during <strong>runtime</strong>.</p><pre>console.log(typeof 42);<br>// Expected log: &quot;number&quot;</pre><p>When used in a condition, TypeScript is able to narrow the type of the object.</p><pre>if(typeof input === &quot;string&quot;) {<br>    // input is narrowed to the type string<br>    submit(input.toLowerCase());<br>}</pre><p>This expression allows TypeScript to predict that input can only be a string in this scope.</p><blockquote><em>While assertions tells TypeScript to trust the developer,<br>narrowing expressions infers types from the runtime logic.</em></blockquote><h4>Discrimination</h4><p>While TypeScript can narrow types with <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html">many other expressions</a>, this only makes sense when refining either unions or primitive types. I call that “types discrimination”.</p><pre>type Fish = { swim: () =&gt; void };<br>type Bird = { fly: () =&gt; void };<br> <br>function move(animal: Fish | Bird) {<br>  if (&quot;swim&quot; in animal) {<br>    // input is narrowed to the type Fish<br>    return animal.swim();<br>  }<br>  // input is narrowed to the type Bird<br>  return animal.fly();<br>}</pre><p>With the above example, the keyword in allows TypeScript to discriminate the type of the animal object.</p><p>With unkown data, types discrimination can be a waste of time:</p><pre>if(typeof input !== &quot;string&quot;) {<br>    // input is still unkown<br>}</pre><p>This means we <strong>cannot</strong> rely exclusively on type narrowing expressions for external data. We need another way to narrow the type down: <strong>data validation</strong>.</p><h3>Zod to the rescue</h3><p><a href="https://github.com/colinhacks/zod">Zod</a> at its core, is an object schema validation tool. This means that it can ensure, on <strong>runtime</strong>, the validity of any given object with a defined schema.</p><h4>Declaring the schema</h4><p>The first thing to do with Zod is to define the schema.</p><pre>import * as z from &quot;zod&quot;;<br><br>const userSchema = z.object({<br>    id: z.number(),<br>    name: z.string(),<br>    age: z.number().optional()<br>}).strict();</pre><p>You might be familiar with this approach if you’ve used other validation tools like <a href="https://github.com/jquense/yup">yup</a> or <a href="https://github.com/sideway/joi">joi</a> before. Zod provides multiple functions (like object(), string()), each returning a Zod schema that <strong>can be combined</strong> in a bigger schema.</p><p>Each piece of schema can be “refined” using methods (like .optional()) which can be queued to obtain complex validation rules.</p><blockquote><em>Thanks to Zod popularity, you can find </em><a href="https://zod.dev/?id=x-to-zod"><em>many tools</em></a><em> to help you convert your existing types and interfaces into Zod schemas. I also like the </em><a href="https://transform.tools/json-to-typescript"><em>transform.tools</em></a><em> website to quickly convert a JSON file into Zod schemas.</em></blockquote><h4>Using the schema</h4><p>The schema provides essentially two ways to validate data. The .parse() method, which can throw errors, and the .safeParse() method:</p><pre>const result = userSchema.safeParse(input);<br>if (!result.success) {<br>  result.error;<br>} else {<br>  result.data; // data type is infered from userSchema<br>}</pre><p>Either the parse fails or the parse returns the object which matches the defined validation schema. In that case, <strong>the object inherits</strong> the type inferred from <strong>the schema structure</strong>.</p><h4>Inferring a type from a schema</h4><p>Generally, data is shared across multiple scopes and contexts. For this reason, we usually declare a type alias once and then use it everywhere the data goes. Zod provides the z.infer&lt;&gt; generic to access the type inferred from a schema.</p><pre>type Article = z.infer&lt;typeof articleSchema&gt;;</pre><blockquote><em>Zod allows to define complex validation rules, such as checking the length of the string: </em>z.string().min(6)</blockquote><blockquote><em>Those rules have no equivalent in TypeScript logic and are translated into the closest type, in this case: </em><em>string.</em></blockquote><h3>Practical Zod uses</h3><p>So, where would you use Zod in your TypeScript project?</p><h4>Parsing API response</h4><blockquote>“Never trust the backend” <em>— Every front-end developers</em></blockquote><p>The main source of unknown/unpredictable data is an API response. You can manually validate the data coming from a fetch promise.</p><pre>fetch(getArticle)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; {<br>    return articleSchema.parse(data);<br>  })<br>  .catch(console.error);</pre><p>You can also use a dedicated library like <a href="https://github.com/ecyrbe/zodios">Zodios</a> (a lib based on axios) to do that.</p><blockquote><em>Because you have no control over the incoming data structure, you may want to make the external data more consistent with your project conventions and logic. Zod provides the </em><a href="https://github.com/colinhacks/zod/tree/v3#transform"><em>.transform() method</em></a><em> to do this during validation.</em></blockquote><h4>Validating form data</h4><p>Another source of external data is user inputs. Zod provides some built-in utils for string validation. You can, of course, implement your own rules using the <a href="https://github.com/colinhacks/zod/tree/v3#refine">.refine() method</a>.</p><pre>const myString = z.string().refine((val) =&gt; val.length &lt;= 255, {<br>  message: &quot;String can&#39;t be more than 255 characters&quot;,<br>});</pre><p>If you are using React, you can use Zod schemas for form validation in <a href="https://react-hook-form.com/docs/useform#resolver">react hook form</a>.</p><h4>Discriminating types?</h4><p>I started using Zod with <a href="https://github.com/colinhacks/zod/tree/v1#type-guards">version 1</a>. This version included a .check() method which allowed to use a schema as a <strong>type guard</strong>, which would be used in a condition for type discrimination.</p><p>Because of this feature, it was tempting to go for the “full-schema” approach and use Zod <strong>for both</strong> validation and type discrimination. However, taking this approach quickly turned out to be <strong>a waste of time</strong>.</p><p>This method has since been removed from the next version of the library. This is a good thing because <strong>Zod now focuses on its original purpose</strong>: external data validation. Type narrowing expressions prove sufficient for most situations for type discrimination.</p><blockquote><em>If you really feel limited with native expressions and the if/else statements syntax, you might also want to take a look at </em><a href="https://github.com/gvergnaud/ts-pattern"><em>ts-pattern</em></a></blockquote><h3>Summary</h3><p>TypeScript is too permissive out of the box. For safer code, external data (unknown by nature) must be validated with tools like Zod. Zod is most useful for validating unpredictable data like form inputs or API response. For most other scenarios, however, type narrowing expressions should be sufficient.</p><p>To find out more about data validation, please check <a href="https://medium.com/ekino-france/zod-the-truth-about-data-validation-7de964f581fd">the sequel to this article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c1583df089" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ekino-france/zod-why-youre-using-typescript-wrong-b0c1583df089">Zod: Why you’re using Typescript wrong</a> was originally published in <a href="https://medium.com/ekino-france">ekino-france</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>