<?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 Sasun Stepanyan on Medium]]></title>
        <description><![CDATA[Stories by Sasun Stepanyan on Medium]]></description>
        <link>https://medium.com/@sasunstepanyan?source=rss-581cea10aae3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UUSFdyEOR7qqC2vzJRwXsw.jpeg</url>
            <title>Stories by Sasun Stepanyan on Medium</title>
            <link>https://medium.com/@sasunstepanyan?source=rss-581cea10aae3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:47:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sasunstepanyan/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 Decorators: Dependency Injection]]></title>
            <link>https://medium.com/@sasunstepanyan/typescript-decorators-dependency-injection-5c23fd692a6?source=rss-581cea10aae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c23fd692a6</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sasun Stepanyan]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 15:43:27 GMT</pubDate>
            <atom:updated>2021-07-13T15:43:27.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="TypeScript" src="https://cdn-images-1.medium.com/max/1024/1*C52-EyqZCqorEgVVaAcKtw.png" /></figure><p>In this article, we’ll take a look under the hood, and learn how the TypeScript compiler transforms decorators to a native JS code. We’ll focus only on class decorators and see how we can use generated <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#metadata">metadata</a> to implement dependency injection.</p><h4>Decorators</h4><p>A <em>Decorator</em> is a special kind of declaration that can be attached to a <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators">class declaration</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators">method</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#accessor-decorators">accessor</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#property-decorators">property</a>, or <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators">parameter</a>. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.</p><p>Decorators are a <a href="https://github.com/tc39/proposal-decorators">stage 2 proposal</a> for JavaScript and are available as an experimental feature of TypeScript. To enable experimental support for decorators, you must enable the experimentalDecorators compiler option either on the command line or in your tsconfig.json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4fa4c7f05ccacc4ea96279daab0550c/href">https://medium.com/media/f4fa4c7f05ccacc4ea96279daab0550c/href</a></iframe><p>TypeScript includes experimental support for emitting certain types of metadata for declarations that have decorators. To enable this experimental support, you must set the emitDecoratorMetadata compiler option either on the command line or in your tsconfig.json:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/973bbd154d4560e84641ae1728b3352b/href">https://medium.com/media/973bbd154d4560e84641ae1728b3352b/href</a></iframe><p>The native JavaScript support for a metadata reflection API is in development. There is a <a href="https://github.com/tc39/proposal-decorators">proposal</a> to add Decorators to ECMAScript, along with a prototype for Reflection API for Decorator Metadata.</p><p>Some of the guys from the TypeScript team have developed a <a href="https://www.npmjs.com/package/reflect-metadata">Polyfill</a> for the prototype of the Reflection API and the TypeScript compiler is now able to emit some serialized design-time type <a href="https://github.com/Microsoft/TypeScript/issues/2577">metadata</a> for decorators. We can use this metadata reflection API polyfill by using the <a href="https://www.npmjs.com/package/reflect-metadata">reflect-metadata</a> package:</p><pre>npm install reflect-metadata</pre><p>We also need to import reflect-metadata in our index.ts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eedcea454de5cb977e399e87b7c2c31/href">https://medium.com/media/3eedcea454de5cb977e399e87b7c2c31/href</a></iframe><p>For the moment there are available only three <strong>reflect metadata design keys</strong>:</p><ul><li><strong>Type metadata</strong> uses the metadata key design:type.</li><li><strong>Parameter type metadata</strong> uses the metadata key design:paramtypes.</li><li><strong>Return type metadata</strong> uses the metadata key design:returntype.</li></ul><h4>Dependency Injection</h4><p>In case you have no idea what DI is, I highly recommend to get <a href="https://en.wikipedia.org/wiki/Dependency_injection">in touch</a> with it. Since this post should not be about the <em>What?</em> but more about the <em>How?</em> let’s try to keep this as simple possible at this point:</p><blockquote><em>Dependency injection is a technique whereby one object supplies the dependencies of another object.</em></blockquote><p>What does that mean? Instead of manually constructing your objects some <em>piece</em> (often called <em>Injector</em>) of your software is responsible for constructing objects.</p><p>Imagine the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45757c6f7d81566ba3618ce97733a05d/href">https://medium.com/media/45757c6f7d81566ba3618ce97733a05d/href</a></iframe><p>To get an instance of Example you&#39;d need to construct it the following way:</p><pre>const example = new Example(new Service1(), new Service2(new Service1()));</pre><p>By using an <em>Injector</em>, which is responsible for creating objects, you can simply do something like:</p><pre>const example = Injector.resolve&lt;Example&gt;(Example);</pre><p>We will implement our very own (and very basic) <em>Injector</em>. In case you&#39;re just looking for some existing solution to get DI in your project you should take a look at <a href="http://inversify.io/">InversifyJS</a>, a pretty neat IoC container for TypeScript.</p><p>What we’re going to do is we’ll implement our very own <em>Injector</em>, which is able to resolve instances by injecting all necessary dependencies. But how we can know about dependencies of a class at runtime? Well, here comes the reflect-metadata package. We can read metadata about class constructor by:</p><pre>Reflect.getMetadata(&#39;design:paramtypes&#39;, Example); </pre><p>It will return undefined, because TypeScript will not emit metadata about class if it has not been decorated. As in this <a href="https://github.com/Microsoft/TypeScript/pull/2589">PR</a> it explicitly was designed to emit metadata just if there is a decorator on a class. So we need a decorator in order our class do emit metadata. Let’s implement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/058e6592edc1baa718d5122195aae7b8/href">https://medium.com/media/058e6592edc1baa718d5122195aae7b8/href</a></iframe><p>Let’s have a look at <em>interface </em>Type&lt;T&gt;: It’s generic type for constructors. Class decorators receive as <em>target</em> argument constructor of class. The Injectable decorator does nothing but logs metadata design:paramtypes of class constructor it’s applied to.</p><p>Back to our example: after applying Injectable decorator to Example class TypeScript will emit metadata about that class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c64628ba6a498237b611c904292e6a8e/href">https://medium.com/media/c64628ba6a498237b611c904292e6a8e/href</a></iframe><p>So now if we call</p><pre>Reflect.getMetadata(&#39;design:paramtypes&#39;, Example); // [ [Function: Service1], [Function: Service2] ]</pre><p>it will return Array of types of dependencies. How this works? Let’s see the generated JavaScript code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0585c1833b8cb073c1429f773c01413/href">https://medium.com/media/e0585c1833b8cb073c1429f773c01413/href</a></iframe><p>On line 28 we can see that at runtime it adds design:paramtypes metadata to Example with value of [Service1, Service2]. It stores this metadata in WeakMap with key of target and value of array. So that we can know which parameters receives Example class constructor.</p><p>Now lets implement our Injector which will find out and resolve dependencies of any class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42ac976b4c03f135c2b995cf00d6a492/href">https://medium.com/media/42ac976b4c03f135c2b995cf00d6a492/href</a></iframe><p>We have a DI container where will be stored instances of dependencies. Our resolve method will receive class constructor as parameter, read dependencies’ types and recursively resolve all dependencies. Let’s get back to our (now slightly extended) example at the beginning and resolve it via the Injector:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb84d95ad54c94ce843337d125c4ff5f/href">https://medium.com/media/fb84d95ad54c94ce843337d125c4ff5f/href</a></iframe><p>Console output:</p><pre>[ [Function: Service1] ]<br>[ [Function: Service1], [Function: Service2] ]<br>Service1<br>Service2</pre><p><em>Wohoo!. </em>Our Injector successfully injected all dependencies. Basically this is how an injector could work. There are still many things to do:</p><ul><li>error handling</li><li>handle circular dependencies</li><li>ability to inject more than constructor tokens</li><li>etc.</li></ul><p>The entire code (including examples and tests) can be found on <a href="https://github.com/sasunstepanyan777/typescript-di">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c23fd692a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>