<?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 Floris Bernard on Medium]]></title>
        <description><![CDATA[Stories by Floris Bernard on Medium]]></description>
        <link>https://medium.com/@flut1?source=rss-562a72cc84aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zYfQGVh5qIHWBNxxLCN7yA.jpeg</url>
            <title>Stories by Floris Bernard on Medium</title>
            <link>https://medium.com/@flut1?source=rss-562a72cc84aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:13:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@flut1/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[Deep-flatten TypeScript types with finite recursion]]></title>
            <link>https://flut1.medium.com/deep-flatten-typescript-types-with-finite-recursion-cb79233d93ca?source=rss-562a72cc84aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb79233d93ca</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Floris Bernard]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 12:00:01 GMT</pubDate>
            <atom:updated>2023-01-15T20:04:27.746Z</atom:updated>
            <content:encoded><![CDATA[<h3>Update: some of the techniques in this article might be outdated 👴</h3><p>To this day I still get really kind reactions to this article 🙂 Thanks for that!</p><p>Please be aware that this article was written for older versions of TypeScript. Some of the workarounds mentioned might not be necessary anymore. For example, I recommend checking out <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#recursive-conditional-types">Recursive Conditional Types</a> in the TypeScript changelog.</p><p>I still hope you enjoy reading my article and get some inspiration for hacking around with TypeScript. So with this disclaimer out of the way, feel free to continue reading 👇</p><p>This week a colleague of mine posed an interesting TypeScript conundrum:</p><blockquote>Can I create a mapped type that extracts all deeply nested properties from an object type into a new flattened type?</blockquote><p>A quick search for “typescript deep flatten type” showed no obvious answers. Even page 2 of Google results showed no hope of a good solution — so the only logical conclusion to draw is that this must be madness. 🤪</p><p>Or… is it? As I had so much fun <a href="https://itnext.io/extracting-decorated-properties-from-classes-in-typescript-caf24aabcb59">the last time</a> I hacked together an Frankenstein solution to a TypeScript problem, I felt I should give this a go too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW5pw5nWCKbvWjeXuXEZMg.png" /></figure><h3>The goal</h3><p>Let’s define the rules of our little challenge. We want to create a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types">mapped type</a> that accepts an arbitrary nested JSON-like type such as this one:</p><pre>/* ExampleInput.ts */<br><br>export type Model = {<br>  foo: number;<br>  bar: string;<br>  baz: {<br>    qux: Array&lt;string&gt;;<br>    quux: {<br>      quuz: number | string;<br>      corge: boolean;<br>    };<br>    flob: number;<br>  };<br>  wobble: {<br>    doop: string;<br>  };<br>};</pre><blockquote><strong>Note on the code snippets</strong>: there used to be CodeSandbox embeds in this article, which allowed you to view feedback from the TypeScript compiler. Unfortunately I had to temporarily replace them with plain code snippets due to an issue with Medium embeds. However, you can still play around with the code in the sandbox through <a href="https://codesandbox.io/s/deep-flatten-typescript-vhip5?file=/src/example-types/ExampleInput.ts">this link</a>.</blockquote><p>The goal is to preserve the primitives and Arrays, but flatten the objects such that the properties are now on root level:</p><pre>/* ExpectedOutput.ts */<br><br>export type ExpectedOutput = {<br>  foo: number;<br>  bar: string;<br>  qux: Array&lt;string&gt;;<br>  quuz: number | string;<br>  corge: boolean;<br>  flob: number;<br>  doop: string;<br>};</pre><h3>Motivation</h3><p>You might be wondering <em>why </em>my colleague wanted to do this. I would love to tell you, but to be honest I forgot. I’m not even sure I asked him, though I’m pretty sure he had good reasons. My reason is I just like messing around with mapped types 🤷🏽‍♂️ So <em>let’s just jump into it</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*I3Pz_kCN2CFV1C2sK1edYg.jpeg" /><figcaption>Example diagram of “it” being jumped into</figcaption></figure><h3>Part 1: Shallow flatten</h3><p>Before we dive into deep flattening a type, let’s simplify the problem by creating a <em>shallow</em> flatten type first. Our type Flatten&lt;T&gt; will be an <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types">intersection</a> of two types:</p><ol><li>All properties of T which aren’t objects</li><li>All the sub-properties T (the properties on object properties of T )</li></ol><p>So our type Flatten will look something like this:</p><pre>type Flatten&lt;T&gt; = NonObjectPropertiesOf&lt;T&gt; &amp; SubPropertiesOf&lt;T&gt;;</pre><h4>1. Non-object properties</h4><p>To find all the keys corresponding to non-object values, we’re going to use an approach similar to the <a href="https://itnext.io/extracting-decorated-properties-from-classes-in-typescript-caf24aabcb59#debe">mapped type from my previous article</a>:</p><pre>type NonObjectKeysOf&lt;T&gt; = {<br>  [K in keyof T]: T[K] extends Array&lt;any&gt; ? <br>    K : <br>    T[K] extends object ? never : K<br>}[keyof T];</pre><p>Note that we explicitly need to include Array&lt;any&gt; before we exclude all objects, because technically Arrays are also objects. Now all that’s left to do is pick these keys out of our original type:</p><pre>type NonObjectPropertiesOf&lt;T&gt; = Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt;;</pre><p>That concludes the first half of our intersection type Flatten&lt;T&gt;. Spoiler alert: the other half is not going to be as easy.</p><h4>2. Sub-properties</h4><p>Let’s first get all the values of our object, then filter them down to the ones of type object while again making the exception for Arrays.</p><pre>type ValuesOf&lt;T&gt; = T[keyof T];<br>type ObjectValuesOf&lt;T&gt; = Exclude&lt;<br>  Extract&lt;ValuesOf&lt;T&gt;, object&gt;, <br>  Array&lt;any&gt;<br>&gt;;</pre><p>We now get a union of all objects on our input type. In our example type, ObjectValuesOf&lt;Model&gt; will give us the union of our object properties Model[&#39;baz&#39;] and Model[&#39;wobble&#39;] .</p><h4>A failed experiment: mapping over a union</h4><p>Let’s try to map over ObjectValuesOf&lt;Model&gt; to get all sub-properties:</p><pre>type SubPropertiesOf&lt;T&gt; = {<br>  [K in keyof ObjectValuesOf&lt;T&gt;]: ObjectValuesOf&lt;T&gt;[K]<br>};</pre><p>Let’s check the type of SubPropertiesOf&lt;Model&gt;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*12Zz8Mijidgyb-Ghpx-rHQ.png" /><figcaption>SubPropertiesOf&lt;Model&gt; = {}</figcaption></figure><p>So this gives us an empty object type. Why? It turns out that keyof ObjectValuesOf&lt;T&gt; is not really what we expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*uW2ghJfZQaHFw9hcNwonPw.png" /><figcaption>keyof ObjectValuesOf&lt;Model&gt; = never?!</figcaption></figure><p>Hmmm… 🤔 what was this never thing again?</p><blockquote>The never type represents the type of values that never occur.<br> — <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html#never">The TypeScript Handbook</a></blockquote><p>So values that represent the keys of our objects never occur? What’s going on here? Well, it turns that keyof T gives us the “<a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types">union of the known, public property names of T</a>”. In the case of the union of our baz and wobble objects, it will only give us the keys that are known to be <strong>on both these objects</strong>. As the baz object doesn’t share any keys with the wobble object, we are left with an empty union aka never. Not very useful for our situation, but it actually makes sense. You want the guarantee that keyof T only gives you known properties of T. If TypeScript were to give you a key that only existed in <em>some</em> cases, like the key “doop” in our example… you might be <em>dooped</em> into a false sense of type safety. (see what I did there?)</p><h4>The intersection of a union</h4><p>Ok, so mapping over ObjectValuesOf&lt;Model&gt; doesn’t really give us what we want. But what do we want anyway? Another way of looking at it is that we want to convert our union Model[&#39;baz&#39;] | Model[&#39;wobble&#39;] into the intersection Model[&#39;baz&#39;] &amp; Model[&#39;wobble&#39;]. Luckily, <a href="https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type/50375286#50375286">an answer on StackOverflow</a> gives us a method to do this:</p><pre>type UnionToIntersection&lt;U&gt; = (U extends any<br>  ? (k: U) =&gt; void<br>  : never) extends ((k: infer I) =&gt; void)<br>  ? I<br>  : never;</pre><p>What kind of sorcery is this? For the details I recommend reading the <a href="https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type/50375286#50375286">original answer</a>, but here is the short rundown:</p><ul><li>The condition U extends any doesn’t really mean much by itself, because all things in life extend any. It’s only there because <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types">conditional types are distributive</a>: we want to have a union of the types (k: U) =&gt; void for every type in U , instead of a single (k: U) =&gt; void for the union of all U.</li><li>Then we use the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#type-inference-in-conditional-types">infer keyword</a> to get an intersection of U. This works because we put U in a function parameter, which is a “contravariant position”. To read more about contravariance, check out <a href="https://www.stephanboyer.com/post/132/what-are-covariance-and-contravariance">this article</a>.</li></ul><h4>Putting it together</h4><p>We now have all the necessary ingredients to brew a shallow Flatten type:</p><pre>/* Flatten.ts */<br><br>import { Model } from &quot;./example-types/ExampleInput&quot;;<br>import {<br>  NonObjectKeysOf,<br>  UnionToIntersection,<br>  ObjectValuesOf<br>} from &quot;./helper-types&quot;;<br><br>type Flatten&lt;T&gt; = Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>  UnionToIntersection&lt;ObjectValuesOf&lt;T&gt;&gt;;<br><br>/* TESTING */<br><br>// this should give no errors<br>const flattenedModel: Flatten&lt;Model&gt; = {<br>  foo: 1,<br>  bar: &quot;abc&quot;,<br>  qux: [&quot;abc&quot;],<br>  quux: {<br>    quuz: 2,<br>    corge: true<br>  },<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>}; // ✅ yay, no errors!<br><br>// this should give errors<br>const incorrectFlattenedModel: Flatten&lt;Model&gt; = {<br>  foo: 1,<br>  // ❌ Type &#39;number&#39; is not assignable to type &#39;string&#39;:<br>  bar: 123,<br>  qux: [&quot;abc&quot;],<br>  // ❌ Property &#39;corge&#39; is missing in type &#39;{ quuz: number; }&#39; but required...<br>  quux: {<br>    quuz: 2<br>  },<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>};</pre><p>This is only part of the solution though. We only flattened our Object one level down. That’s not good enough, we need to go deeper…</p><h3>Part 2: Recursive types</h3><p>In order to also extract the deeply nested properties, we will also need to pass our child objects through Flatten recursively. So all we need to do is pass our object properties ObjectValuesOf&lt;T&gt; through Flatten to make sure they are flattened as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*zd8b3S5vluci6voDHhl-gg.png" /><figcaption>For more information on recursion I highly recommend <a href="https://medium.com/@flut1/deep-flatten-typescript-types-with-finite-recursion-cb79233d93ca">this article</a></figcaption></figure><p>Yeah… turns out the TypeScript compiler doesn’t really like self-referencing types. A quick search for recursive types may point you to a <a href="https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540">comment on the TypeScript Github</a> with a possible solution: reference back using an interface. Maybe something like this:</p><pre>type DeepFlatten&lt;T&gt; = Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>  UnionToIntersection&lt;FlattendObjectValuesOf&lt;T&gt;&gt;;<br>interface FlattendObjectValuesOf&lt;T&gt; <br>  extends DeepFlatten&lt;ObjectValuesOf&lt;T&gt;&gt; {<br>}</pre><p>However, this gives us an error on the interface definition 😭</p><blockquote>❌ An interface can only extend an object type or intersection of object types with statically known members. ts(2312)</blockquote><p>Turns out the solution using interfaces only works for static types, not generic ones. So for now, it doesn’t seem possible to write a DeepFlatten type that references <strong>itself</strong>. But do we really need that?</p><h3>Part 3: Finite recursion</h3><p>A recursive deep flatten would in theory be <em>infinite</em>: it would keep flattening until there is nothing left to flatten. But lets be real: do we really have infinite types in our TypeScript applications? Do we really have types that has object nested more than 4 levels deep? If so, how about 10 levels? 🤨 Probably not. (<em>If you do, fight me in the comments</em>)</p><p>So here’s what I suggest we do: instead of creating a type that references itself, we create <strong>a bunch of types</strong> that reference <strong>each other</strong>. We’ll also use the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types">distributive conditional types</a> (extends any ?) again to make sure our intermediate types are properly distributed:</p><pre>/* deep-flatten.ts */<br><br>import { Model } from &quot;./example-types/ExampleInput&quot;;<br>import {<br>  NonObjectKeysOf,<br>  UnionToIntersection,<br>  ObjectValuesOf<br>} from &quot;./helper-types&quot;;<br><br>type DeepFlatten&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten2&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten2&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten3&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten3&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten4&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten4&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten5&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten5&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten6&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten6&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten7&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten7&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten8&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten8&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>      UnionToIntersection&lt;DeepFlatten9&lt;ObjectValuesOf&lt;T&gt;&gt;&gt;<br>  : never;<br><br>type DeepFlatten9&lt;T&gt; = T extends any<br>  ? Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt;<br>  : UnionToIntersection&lt;ObjectValuesOf&lt;T&gt;&gt;;<br><br>/* TESTING */<br><br>// this should give no errors<br>const flattenedModel: DeepFlatten&lt;Model&gt; = {<br>  foo: 1,<br>  bar: &quot;abc&quot;,<br>  qux: [&quot;abc&quot;],<br>  quuz: 2,<br>  corge: true,<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>}; // ✅ yay, no errors!<br><br>// this should give an error<br>const incorrectFlattenedModel: DeepFlatten&lt;Model&gt; = {<br>  foo: 1,<br>  bar: &quot;abc&quot;,<br>  qux: [&quot;abc&quot;],<br>  quuz: 2,<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>}; // ❌ Property &#39;corge&#39; is missing in type...</pre><p>Yeah I know… not the prettiest of types. But it works! If it makes you feel any better, we can give it a fancy name like “<em>finite recursion</em>”.</p><p>So is there nothing we can do to make it a little less verbose? As far as I can think of, only a little. We can move some of the duplication to a helper type DFBase, and then only have the recursive bit repeat. And we can abbreviate some of our repeating variables so they fit on a single line 😃</p><pre>/* deep-flatten-shorter.ts */<br><br>import { Model } from &quot;./example-types/ExampleInput&quot;;<br>import {<br>  NonObjectKeysOf,<br>  UnionToIntersection,<br>  ObjectValuesOf<br>} from &quot;./helper-types&quot;;<br><br>type DFBase&lt;T, Recursor&gt; = Pick&lt;T, NonObjectKeysOf&lt;T&gt;&gt; &amp;<br>  UnionToIntersection&lt;Recursor&gt;;<br><br>type DeepFlatten&lt;T&gt; = T extends any ? DFBase&lt;T, DF2&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF2&lt;T&gt; = T extends any ? DFBase&lt;T, DF3&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF3&lt;T&gt; = T extends any ? DFBase&lt;T, DF4&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF4&lt;T&gt; = T extends any ? DFBase&lt;T, DF5&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF5&lt;T&gt; = T extends any ? DFBase&lt;T, DF6&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF6&lt;T&gt; = T extends any ? DFBase&lt;T, DF7&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF7&lt;T&gt; = T extends any ? DFBase&lt;T, DF8&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF8&lt;T&gt; = T extends any ? DFBase&lt;T, DF9&lt;ObjectValuesOf&lt;T&gt;&gt;&gt; : never;<br>type DF9&lt;T&gt; = T extends any ? DFBase&lt;T, ObjectValuesOf&lt;T&gt;&gt; : never;<br><br>// this should give no errors<br>const flattenedModel: DeepFlatten&lt;Model&gt; = {<br>  foo: 1,<br>  bar: &quot;abc&quot;,<br>  qux: [&quot;abc&quot;],<br>  quuz: 2,<br>  corge: true,<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>}; // ✅ yay, no errors!<br><br>// this should give an error<br>const incorrectFlattenedModel: DeepFlatten&lt;Model&gt; = {<br>  foo: 1,<br>  bar: &quot;abc&quot;,<br>  qux: [&quot;abc&quot;],<br>  quuz: 2,<br>  flob: 3,<br>  doop: &quot;abcd&quot;<br>}; // ❌ Property &#39;corge&#39; is missing in type...</pre><p>So there it is: the least ugly DeepFlatten I can think of. One might be able to use the same constructs to do other kinds of flattening. Do you have a more elegant solution? Let me know in the comments! 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb79233d93ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting decorated properties from classes in TypeScript]]></title>
            <link>https://itnext.io/extracting-decorated-properties-from-classes-in-typescript-caf24aabcb59?source=rss-562a72cc84aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/caf24aabcb59</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Floris Bernard]]></dc:creator>
            <pubDate>Mon, 20 May 2019 11:48:54 GMT</pubDate>
            <atom:updated>2023-01-15T17:58:53.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf_R6rG2LbDnNA1OUyhpZQ.png" /></figure><p>This is a post about my journey to a complex and hacky answer for an interesting TypeScript question. I’m not sure that this is a method you should actually be using, but I think it’s an interesting approach. If there’s a simpler solution, I’m sure that (as <a href="https://meta.wikimedia.org/wiki/Cunningham%27s_Law">Cunningham’s Law</a> suggests) it will show up in the comments 👇</p><p><em>Note: this story goes into some advanced TypeScript. I’m going to assume you know what decorators, type aliases and generics are.</em></p><h3>The question</h3><blockquote>How do I create a mapped type that extracts only the properties that have been annotated by my property decorator?</blockquote><p>This question is a little abstract so let’s look at it through an example.</p><h4>Our special decorator 🐟</h4><p>Let’s imagine that we have a very important decorator called “special”:</p><pre>/* special.ts */<br><br>function special(target: Object, propertyName: string) {<br>  🐟(target)(🚀, 💯, 🙌, propertyName);<br>}<br>// I have no clue what this does, but it looks very important.</pre><p>And we have some class that uses our decorator:</p><pre>/* SomeModel.ts */<br><br>import special from &quot;./special&quot;;<br><br>export default class SomeModel {<br>  @special foo: number;<br>  @special bar: Array&lt;string&gt;;<br><br>  baz: number;<br>  qux: string;<br>}<br><br>export const model = new SomeModel();</pre><blockquote><strong>Note on the code snippets</strong>: there used to be CodeSandbox embeds in this article, which allowed you to view feedback from the TypeScript compiler. Unfortunately I had to temporarily replace them with plain code snippets due to an issue with Medium embeds. However, you can still play around with the code in the sandbox through <a href="https://codesandbox.io/s/tspropertydecorators-0ht2s?file=/src/SomeModel.ts">this link</a>.</blockquote><h4>The getSpecialProperty util</h4><p>Now we want to create a utility function that gets one of these @special properties from an object:</p><pre>/* getSpecialProperty.ts */<br><br>import { model } from &quot;./SomeModel&quot;;<br><br>function getSpecialProperty&lt;TModel, TKey extends keyof TModel&gt;(<br>  model: TModel,<br>  key: TKey<br>) {<br>  return model[key];<br>}<br><br>/* TESTING */<br>// ✅ works! it even correctly infers type &#39;number&#39;<br>const fooValue = getSpecialProperty(model, &quot;foo&quot;);<br><br>// ❌ this gives an error, as we expected<br>const imaginaryValue = getSpecialProperty(<br>  model,<br>  &quot;imaginary&quot; /* ERROR: Argument of type &#39;&quot;imaginary&quot;&#39; is not assignable to parameter of type &#39;&quot;foo&quot; | &quot;bar&quot; | &quot;baz&quot; | &quot;qux&quot;&#39;. */<br>);<br><br>// 👎 whoops. it allows &#39;qux&#39;, even though it&#39;s not special<br>getSpecialProperty(model, &quot;qux&quot;);</pre><p>As you can see in on the last line, there is a problem with our function. It will also accept a key that has not been annotated with our special decorator. This is the problem we are trying to solve: defining TKey in such a way that it only matches our special decorated properties.</p><h3>Part 1: the nonsolution</h3><p>Let’s quickly acknowledge that there’s a simple method to separate these @special properties out. Just put them on a separate class:</p><pre>/* SomeModel.easy.ts */<br><br>import special from &quot;./special&quot;;<br><br>class Special {<br>  @special foo: number;<br>  @special bar: Array&lt;string&gt;;<br>}<br><br>class SomeModel {<br>  special = new Special();<br><br>  baz: number;<br>  qux: string;<br>}<br><br>function getSpecialProperty&lt;TSpecial, TKey extends keyof TSpecial&gt;(<br>  model: { special: TSpecial },<br>  key: TKey<br>) {<br>  return model.special[key];<br>}</pre><p>However this is not a solution to the problem I was trying to solve. I want to put my “@special” properties on the same object as the other properties. After all, what’s the point of using decorators if I also have to move all my properties to a separate object?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fembed%2F3eKdC7REvgOt2%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fgifs%2Fmumbles-man-im-so-rusty-pillars-of-eternity-3eKdC7REvgOt2&amp;image=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fmedia.giphy.com%2Fmedia%2F3eKdC7REvgOt2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb626cef0f14411ee916778bcedf4fb0/href">https://medium.com/media/fb626cef0f14411ee916778bcedf4fb0/href</a></iframe><h3>Part 2: getting keys by value type</h3><h4>Looking up all numbers</h4><p>Let’s solve an “easier” problem first: getting all the keys from our class TModel that have values of type number . I put “easier” in quotes here because the type alias that does this may still look a little daunting:</p><pre>/* SomeModel.easy.ts */<br><br>/* THIS IS THE TYPE ALIAS */<br>type NumberKeys&lt;T&gt; = {<br>  [K in keyof T]: T[K] extends number ? K : never<br>}[keyof T];<br><br>/* BROKEN DOWN EXPLANATION + EXAMPLE */<br>type ExampleInput = { a: number; b: string; c: number };<br><br>// this will convert key-value pairs into key-key pairs<br>type MapValuesToKeys&lt;T&gt; = { [K in keyof T]: K };<br>// MapValuesToKeys&lt;ExampleInput&gt; = { a: &quot;a&quot;; b: &quot;b&quot;; c: &quot;c&quot;; }<br><br>// this will do the same, but map non-numbers to &#39;never&#39;<br>type MapNumbersToKeys&lt;T&gt; = {<br>  [K in keyof T]: T[K] extends number ? K : never<br>};<br>// MapNumbersToKeys&lt;ExampleInput&gt; = { a: &quot;a&quot;; b: never; c: &quot;c&quot;; }<br><br>// the last step is to take the above, and get a union of the values<br>// (note that &#39;never&#39; gets stripped from union types)<br>type FinalStep&lt;T&gt; = MapNumbersToKeys&lt;T&gt;[keyof T];<br>// FinalStep&lt;ExampleInput&gt; = &quot;a&quot; | &quot;c&quot;</pre><h4>Making it more generic</h4><p>We can generalize our NumberKeys type alias to get the keys of any given type:</p><pre>type KeysOfType&lt;TTarget, TValue&gt; = {<br>  [K in keyof TTarget]: TTarget[K] extends TValue ? K : never<br>}[keyof TTarget];</pre><p>Great! So now all we need is to use this type alias to filter by the type of our special properties, and we’re done! 🥳</p><p>Well… therein lies the problem 😟. Our properties foo and bar may have special decorator, but their types are just regular number and Array&lt;string&gt; . And (at the time of writing) TypeScript doesn’t let you mutate the type of something with a decorator. It has a <a href="https://github.com/Microsoft/TypeScript/issues/4881">lengthy issue on Github</a>, and it seems like this isn’t going to be resolved anytime soon. This leaves us with no choice but to explicitly change the types of our decorated properties.</p><h3>Part 3: creating a “Special” type</h3><p>Let’s create a new type Special that has some property on it that makes it distinguishable from other types. We can make something up, as we’re not really going to use it at runtime 🤷‍♂️. Let’s also modify our @special decorator such that it can no longer be used with properties that aren’t Special</p><pre>/* SpecialType.ts */<br><br>export interface IsSpecial {<br>  __imAUniqueSnowflake: true;<br>}<br><br>// I guess you could say this is my specialty<br>export type Special&lt;T&gt; = T &amp; IsSpecial;<br><br>// By typing our @special decorator like this,<br>// decorated property need type &#39;IsSpecial&#39;<br>export function special&lt;<br>  TKey extends string,<br>  TTarget extends { [K in TKey]: IsSpecial }<br>&gt;(target: TTarget, propertyName: TKey) {<br>  // implementation here<br>}</pre><p>Here is a model that uses our new type:</p><pre>/* SpecialTypeClass.ts */<br><br>import { special, Special } from &quot;./SpecialType&quot;;<br><br>class SomeModel {<br>  @special foo: Special&lt;number&gt;;<br>  @special bar: Special&lt;Array&lt;string&gt;&gt;;<br><br>  baz: number;<br>  qux: string;<br>}<br><br>/* TESTING */<br>const model = new SomeModel();<br><br>logNumber(model.foo); // ✅ OK<br>model.foo = 5; // ❌ ERROR: Type &#39;5&#39; is not assignable to type &#39;Special&lt;number&gt;&#39;. Type &#39;5&#39; is not assignable to type &#39;IsSpecial&#39;.ts(2322)<br>model.bar = [&quot;abc&quot;]; // ❌ ERROR Type &#39;string[]&#39; is not assignable to type &#39;Special&lt;string[]&gt;&#39;. Property &#39;__imAUniqueSnowflake&#39; is missing in type &#39;string[]&#39; but required in type &#39;IsSpecial&#39;.<br><br>function logNumber(n: number) {<br>  console.log(n);<br>}</pre><p>Unfortunately we have introduced a new problem 😩. We can use still pass model.foo and model.bar to functions that expect number and Array&lt;string&gt; , but we can no longer update foo and bar with values that haven’t been cast to Special . This may be an acceptable trade-off when you define initial values on the class, but not very practical when using the model throughout your application.</p><blockquote>This seems like a catch-22: we want to change the type of @special decorated properties so we can extract them, but every change makes them incompatible with our original types.</blockquote><h3>Part 4: back to the drawing board</h3><h4>Unacceptable?</h4><p>So we started out with a method that was inadequate: putting the properties on a separate object. Then we moved to trying to extract our properties using special types. This seems to render our class completely useless. But what if we combined these to methods into one Frankenstein-like master hack? 🤔Surely, that will solve our issue.</p><p>🦹‍♂ ️Here is our evil master plan:</p><ol><li>Define the @special decorated properties of our class with a Special type</li><li>Use the Special type to extract the decorated properties on the class</li><li>Create a <strong>new type</strong> that transforms all the decorated properties back to their original type <em>but also</em> adds a separate object with only the decorated properties</li><li>Trick typescript into thinking that our original class is actually of this new type 👌</li></ol><h4>Our final model</h4><p>This is what our final model will look like:</p><pre>/* FinalModel.ts */<br><br>import { special, Special } from &quot;./SpecialType&quot;;<br>import WithSpecial from &quot;./WithSpecial&quot;;<br><br>class FinalModel {<br>  @special foo: Special&lt;number&gt;;<br>  @special bar: Special&lt;Array&lt;string&gt;&gt;;<br><br>  baz: number;<br>  qux: string;<br>}<br><br>export default (FinalModel as unknown) as WithSpecial&lt;<br>  typeof FinalModel<br>&gt;;</pre><p>Note that the last line already contains step 4️⃣ of our evil masterplan. It exports FinalModel but with a slight modification. First, it makes TypeScript forget everything it knows about the class by casting it to <em>the unknown</em>. 🕶</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fembed%2F374pcIBVEGb6g%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fgiphy.com%2Fgifs%2Fmen-in-black-memory-no-worries-374pcIBVEGb6g&amp;image=https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttps%2Fmedia.giphy.com%2Fmedia%2F374pcIBVEGb6g%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/98c0db1b6cb1a8aa340714a05eb7d432/href">https://medium.com/media/98c0db1b6cb1a8aa340714a05eb7d432/href</a></iframe><p>Second, we replace the type with our own interpretation. This is what as WithSpecial&lt;typeof FinalModel&gt; does. What I like about this final solution is that our model looks quite clean and readable. Sure we have to sprinkle in some Special typings in our class declaration, but our decorator signature will ensure that we don’t forget that. We still have to write WithSpecial though, which is where all dirty hacks will take place. So let’s hide that in a separate module where nobody will ever find it. 🤫</p><h4>Transforming the class definition</h4><p>So how <em>do</em> we transform a class definition? It comes down to 2 things: mapping over the static properties and transforming the constructor to make it return our modified instance type:</p><pre>/* WithSpecial.ts */<br><br>import TransformSpecial from &quot;./TransformSpecial&quot;;<br><br>// type that will match any class (constructor)<br>type AnyConstructor = new (...args: Array&lt;any&gt;) =&gt; any;<br><br>// extract the type of the arguments of a constructor function<br>type ConstructorArgs&lt;T&gt; = T extends new (...args: infer A) =&gt; any<br>  ? A<br>  : never;<br><br>type WithSpecial&lt;T extends AnyConstructor&gt; = {<br>  // include any static properties on the class<br>  [K in keyof T]: T[K]<br>} &amp; {<br>  // type a constructor with the original arguments,<br>  // but return a transformed instance<br>  new (...args: ConstructorArgs&lt;T&gt;): TransformSpecial&lt;<br>    InstanceType&lt;T&gt;<br>  &gt;;<br>};<br><br>export default WithSpecial;</pre><h4>Transforming the class instance</h4><p>Now lets define our new instance type. All Special properties will be mapped back to their original types. Additionally, we make up a new property called __special . This doesn’t really exist at runtime, but TypeScript will think it does. We can exploit this to still have access to all the names of the Special properties, even though the properties themselves are now back to normal.</p><pre>/* TransformSpecial.ts */<br><br>import { Special } from &quot;./SpecialType&quot;;<br><br>// leftover from previous experiment<br>// gets all keys of &#39;TTarget&#39; where the value has type &#39;TValue&#39;<br>type KeysOfType&lt;TTarget extends object, TValue&gt; = {<br>  [K in keyof TTarget]: TTarget[K] extends TValue ? K : never<br>}[keyof TTarget];<br><br>type TransformSpecial&lt;T extends object&gt; = {<br>  // map over all properties. If they are special, transform them back<br>  [P in keyof T]: T[P] extends Special&lt;infer A&gt; ? A : T[P]<br>} &amp; {<br>  // define a new property, __special<br>  // this will only contain all the Special properties<br>  __special: Pick&lt;T, KeysOfType&lt;T, Special&lt;unknown&gt;&gt;&gt;;<br>};<br><br>// we can use this to extract Special properties from our transformed class<br>export type HasSpecial = { __special: object };<br>export type SpecialKeys&lt;T extends HasSpecial&gt; = keyof T[&quot;__special&quot;];<br><br>export default TransformSpecial;</pre><h4>The new and improved getSpecialProperty</h4><p>Now that we have a class where our properties have normal types, and we have a util to extract all decorated properties, we can finally create our improved version of getSpecialProperty 😀</p><pre>/* getSpecialProperty.fixed.ts */<br><br>import FinalModel from &quot;./FinalModel&quot;;<br>import { SpecialKeys, HasSpecial } from &quot;./TransformSpecial&quot;;<br><br>function getSpecialProperty&lt;<br>  TModel extends HasSpecial,<br>  TKey extends SpecialKeys&lt;TModel&gt;<br>&gt;(model: TModel, key: TKey): TModel[TKey] {<br>  return model[key];<br>}<br><br>/* TESTING */<br>const model = new FinalModel();<br><br>// ✅ still works<br>const fooValue = getSpecialProperty(model, &quot;foo&quot;);<br>// ❌ Gives an error now, because &quot;qux&quot; is not special!<br>const quxValue = getSpecialProperty(<br>  model,<br>  &quot;qux&quot; /* Argument of type &#39;&quot;qux&quot;&#39; is not assignable to parameter of type &#39;&quot;foo&quot; | &quot;bar&quot;&#39;. */<br>);</pre><p>And with that error on qux, our search has come to an end. 🎉🎈🎊👯‍♂️</p><p>We have achieved our goal of type-checking for decorated properties, and we can now finally rest. 😴</p><h3>Q&amp;A</h3><blockquote>Is there an easier way to achieve this?</blockquote><p>Maybe</p><blockquote>Should I be using this hack?</blockquote><p>Probably not</p><blockquote>Can I structure my code such that I don’t run into this issue at all?</blockquote><p>Definitely</p><blockquote>Was this worth it?</blockquote><p><strong>Absolutely</strong></p><blockquote>I just scrolled to the bottom because I don’t want to read your long story. Can I just have a copy-paste generic version that is able to annotate and extract any set of properties? Even if I don’t use decorators?</blockquote><p>Here you go:</p><pre>/* generic.ts */<br><br>// use this to test if a class is transformed or if a property is a special attribute<br>type WithAttribute&lt;TAttr extends string&gt; = { [K in TAttr]: object };<br>// a generic version of the special attribute type<br>type AttributeType&lt;TAttr extends string = string, TVal = unknown&gt; = {<br>  value: TVal;<br>} &amp; WithAttribute&lt;TAttr&gt;;<br>// extract all the special attributes of a transformed class<br>type AttributeKeysOf&lt;<br>  TAttr extends string,<br>  TModel extends WithAttribute&lt;TAttr&gt;<br>&gt; = keyof TModel[TAttr];<br><br>// transform a class with typed attributes<br><br>// prettier-ignore<br>type WithAttributes&lt;TModel extends new (...args: Array&lt;any&gt;) =&gt; any, TAttr extends string&gt; = {<br>  [K in keyof TModel]: TModel[K] <br>} &amp; {<br>  new (...args: TModel extends new (...args: infer A) =&gt; any ? A : never): {<br>    [P in keyof InstanceType&lt;TModel&gt;]: InstanceType&lt;TModel&gt;[P] extends AttributeType&lt;TAttr, infer A&gt; ? A : InstanceType&lt;TModel&gt;[P]<br>  } &amp; {<br>    [K in TAttr]: Pick&lt;InstanceType&lt;TModel&gt;, {<br>      [K in keyof InstanceType&lt;TModel&gt;]: InstanceType&lt;TModel&gt;[K] extends AttributeType&lt;TAttr, any&gt; ? K : never<br>    }[keyof InstanceType&lt;TModel&gt;]&gt;<br>  };<br>};<br><br>/* EXAMPLE USAGE -- creating an Ultra special attribtue */<br><br>// create our special attribute type &#39;Ultra&#39;<br>// it doesn&#39;t really matter what string you put here, as long as it&#39;s unique<br>type UltraId = &quot;__ultra&quot;;<br>type Ultra&lt;T&gt; = AttributeType&lt;UltraId, T&gt;;<br>type UltraKeysOf&lt;T extends WithAttribute&lt;UltraId&gt;&gt; = AttributeKeysOf&lt;<br>  UltraId,<br>  T<br>&gt;;<br><br>/* EXAMPLE USAGE -- create a setter to set Ultra special attributes */<br>function setSpecialProperty&lt;<br>  TModel extends WithAttribute&lt;UltraId&gt;,<br>  TKey extends UltraKeysOf&lt;TModel&gt;<br>&gt;(model: TModel, key: TKey, value: TModel[TKey]) {<br>  model[key] = value;<br>}<br><br>/* EXAMPLE USAGE -- creating a model with Ultra special attributes */<br>// don&#39;t use this one -- this is the base model<br>class BaseModel {<br>  ultraNumber: Ultra&lt;number&gt;;<br>  ultraString: Ultra&lt;string&gt;;<br><br>  regularNumber: number;<br>  someArray: Array&lt;string&gt;;<br>}<br>// use this one<br>const Model = (BaseModel as unknown) as WithAttributes&lt;<br>  typeof BaseModel,<br>  UltraId<br>&gt;;<br>type Model = InstanceType&lt;typeof Model&gt;;<br><br>/* TESTING THE EXAMPLE */<br>const model: Model = new Model();<br><br>setSpecialProperty(model, &quot;ultraNumber&quot;, 5); // ✅ compiles<br>setSpecialProperty(model, &quot;ultraNumber&quot;, &quot;5&quot;); // ❌ Error, value should be number<br>setSpecialProperty(model, &quot;ultraString&quot;, &quot;5&quot;); // ✅ compiles<br>setSpecialProperty(model, &quot;ultraString&quot;, 5); // ❌ Error, value should be string<br>setSpecialProperty(model, &quot;regularNumber&quot;, 5); // ❌ Error, regularNumber is not Ultra<br>setSpecialProperty(model, &quot;someArray&quot;, [&quot;abc&quot;]); // ❌ Error, someArray is not Ultra<br><br>const logNumber = (n: number) =&gt; console.log(n);<br>logNumber(model.ultraNumber); // ✅ ultraNumber is still of type number<br>model.ultraNumber = 5; // ✅ still able to assign numbers to ultraNumber<br><br>/* EXAMPLE USAGE - limiting a decorator to Ultra typings */<br>function ultra&lt;<br>  TKey extends string,<br>  TTarget extends { [K in TKey]: Ultra&lt;unknown&gt; }<br>&gt;(target: TTarget, propertyName: TKey) {<br>  // decorator implementation here<br>}<br><br>class DecoratedModel {<br>  @ultra someProperty: number; // ❌ Error, property has to have Ultra type<br>  @ultra anotherOne: Ultra&lt;number&gt;; // ✅ compiles<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf24aabcb59" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/extracting-decorated-properties-from-classes-in-typescript-caf24aabcb59">Extracting decorated properties from classes in TypeScript</a> was originally published in <a href="https://itnext.io">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>