What methods do typescript libraries use to interpret types during runtime?

After compiling source code from TypeScript to JavaScript, type annotations are removed and it becomes impossible to verify the type of a variable at runtime.

Despite this limitation, there exist TypeScript libraries that alter their behavior based on the type annotations of class properties. For instance, when defining TypeORM entities, developers may create something like:

@Entity()
class MyEntity extends BaseEntity {
  @Field()
  public id: number // automatically determines int database type

  @Field()
  public description: string // automatically infers varchar or text database type

  @Field()
  public image: string | null // unable to infer correct type, causing an error

}

We can observe similar functionality in typedi (passing the correct reference through constructors), type-graphql (constructing the GraphQL schema with accurate GraphQL types), and so forth. While it's understandable when a function needs to be passed through a decorator or related structure, how do these libraries deduce types solely from type annotations?

Answer №1

My curiosity led me to discover the answer within the TypeORM documentation here:

TypeScript configuration

Upon further investigation, it is crucial to ensure that TypeScript version 4.5 or above is being used, and that the following settings are enabled in the tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

From my understanding, these settings instruct TypeScript to provide runtime type information to decorators. This fact is confirmed here:

Emit Decorator Metadata

emitDecoratorMetadata

This option enables experimental support for emitting type metadata for decorators, which synergizes with the module reflect-metadata.

Once this feature is activated, TypeScript generates calls to decorators that include type details during runtime. An exemplary scenario provided in the documentation involves the following code snippet:

class Demo {
  @LogMethod
  public foo(bar: number) {
    // do nothing
  }
}

This results in the emission of __decorate and __metadata functions, transforming the code as follows:

class Demo {
    foo(bar) {
        // do nothing
    }
}
__decorate([
    LogMethod,
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number]),
    __metadata("design:returntype", void 0)
], Demo.prototype, "foo", null);

In comparison to the given example, the decorator calls in your scenario emit the following output:

__decorate([
    Field(),
    __metadata("design:type", Number)
], MyEntity.prototype, "id", void 0);
__decorate([
    Field(),
    __metadata("design:type", String)
], MyEntity.prototype, "description", void 0);
__decorate([
    Field(),
    __metadata("design:type", Object)
], MyEntity.prototype, "image", void 0);
MyEntity = __decorate([
    Entity()
], MyEntity);

Explore more insights through this Playground link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating the JqueryUI menu into an AngularJS project

We are facing an issue with integrating JqueryUI menus into our AngularJS application. In our Layout.js file, we are attempting the following: OURApp.controller('leftBarCtrl', ['$scope', function ($scope) { $scope.init = function ( ...

Using jQuery's .load() method is like including a file in a

Currently, Im working on revamping a company website that comes equipped with its very own CMS. Unfortunately, we are restricted from accessing the server configuration and FTP, which means I am limited to running only client-side files like HTML/CSS/J ...

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

Utilizing Laravel5 to create captivating Highmaps visuals

Good day! I am currently setting up my database to work with HighMaps using Laravel5. I have received JSON data from Laravel in the following format: [{"hc-key":"es-vi"},{"hc-key":"es-cs"},{"hc-key":"es-lo"},{"hc-key":"es-z"}] Highmaps requires the data ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

JavaScript object containing the individual points of each person extracted using Regex form

Here is the string that I'm working with: Phantom_FR - 5 Points\n\nmineblox17,Dominus_Loading - 0 Points\n\ndavidroks528,beeks567,JohnDoe54631 - 4 Points\n\n\n\n **PLEASE ARCHIVE THIS CARD WHEN YOU ARE FINISHED ...

Looking to validate a text box and use JavaScript to redirect to a specific URL?

I've been attempting to create a "password protected" page for my customers to track the progress of their page, but it should only be accessible with a specific code. After spending several hours on this task, I have managed to display a popup scree ...

What is the best way to verify nested objects with a generic type?

Consider a scenario where I have a generic type defined as follows: type Item<T> = {a:T; B:T} In this case, I aim to automatically determine an object with consistent fields types without explicitly stating the generic type: const items: Record<s ...

Confirm the data in each field of a form individually

I am facing an issue with a form that contains 7 fields. When I submit the form to the "register.php" page, it processes each field one by one and outputs the result as a whole. However, I need to validate the data using ajax, collect the output one by one ...

Is it appropriate to include JavaScript and CSS in views?

In my ASP.NET MVC project, I have set up a _Layout, a controller, and several views. Certain pieces of code are clearly global in nature, such as the CSS included in the _Layout file and other styles that are consistent throughout the site. However, when ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Setting up OpenID configuration in angular-oauth2-oidc to bypass authentication for certain addresses

In my Angular project, I implemented OpenID authentication using the angular-oauth2-oidc project. However, I need to disable authentication for certain routes. To achieve this, I start the code flow in the main component and bootstrap it in the main modu ...

`Welcome to the World of AngularJS with IntelliJ IDEA`

Hey there! I'm currently diving into the world of Angular.js and IntelliJ IDEA, but seems like I've hit a roadblock. I'm attempting to create a basic "hello world" example from a book in the IDE, but it's just not cooperating. After dow ...

What is the best way to extract data from a JSON file using Java?

I am working with a JavaScript file that contains the following object: var MoceanSettings={ BannerURL:'', IsDirectWall:true, AppOfDayZone:156431, ImpressTrackUrl:null, ClickTrackUrl:null, Categories:[ ...

Disabling CSS transitions and attempting to alter the style of an HTML element using JavaScript may not consistently work as expected

Currently, I am in the process of creating an animated effect for a website that involves moving two elements' positions over time and resetting them to their original position. Only one element is displayed at a time, and the animation should run smo ...

Error message: "An unauthorized signature detected during LemonSqueezy Webhooks integration"

When a payment is successfully made using the LemonSqueezy API, a webhook sends a payload. However, I am encountering an issue with verifying the signature. For more information, you can refer to this documentation: Below is my TypeScript code for a post ...

I am a newcomer to HTML and I am eager to display the selected options from a <select> element

Can someone help me display the selected licorice flavor, chocolate color, and topping? For example: "Green apple, white, christmas sprinkles." I'm not sure if assigning a numeric value to each option is necessary. I did it on a whim. Please suggest ...

The module 'node:fs' could not be located. Stack required:

I've been developing a Teams app with my tab in React and TypeScript. (In case you're unfamiliar, the tab can be seen as an individual React app) Currently, I'm setting up linting using ESLint and Prettier. I have successfully run the scri ...

Transforming a class component into a functional component using React for a session

While working on a React application, I encountered the need for auto logout functionality for inactive users. After referring to this resource, I attempted to convert my class component code to functional components. However, I faced issues as the functio ...