DEV Community

Cover image for Typescript to JavaScript post compile
John Peters
John Peters

Posted on • Updated on

Typescript to JavaScript post compile

Imagine something like the Angular class/component shown here. It's a component that draws a circle with text in it.

When compiled the Javascript looks like this:

compiled to javascript

We can see that the @Input() properties of Angular wind up in the function CircleTextComponent using the keyword this. e.g. this.radius, this.backGround etc. Notice that the javascript equivalent does not need the type of string. This is because the loosely typed javascript employs "implicit cohersion". Nice...

The keyword 'this' means this-object. Therefore; this.radius means this CircleTextComponent's radius property.

The input keywords in Angular allow other users of this component to inject the values they want. Like this:

CircleWithText

We know that app-circle-text HTML custom tag works, because our component defined it in the selector section below.

componentDecorator

An Angular concept for sure...

Models

Many of today's JavaScript experts don't use models at all! What? Yes, instead they use the power of Javascript objects instead. They may prefer the object.assign method Or even dynamically create objects where needed; each time using key:value pairs that are not known by the IDE.
e.g. let person = {lastname:"somename"}
The IDE has no concept if the key spelling or value type is correct. Only subsequent uses of this object allows the IDE auto-complete setting the values. But it will never catch value type errors.

The problem of not using models in JavaScript is summed up asking these questions: "How many person objects were created, where are they, and were any keys misspelled and do they all exactly have all the same key names? And what about the values, were they all of the same type? In other words are you only going to find those types of errors at run-time! Ouch...

There's a better way. If we are using Typescript for your models. Our circle model would look like this:
circlemodel
And now our IDE (Visual Studio Code) can do pre-compile time type checking as shown here.
typechecking

Notice that backGround is in red! This is because we put in a number and not a string. But the best part is that we don't have to discover this at run time as the Typescript compiler will flag this as an error.

Typescript models are great to keep key names all the same, all the values to only what they should be type wise.

This is why I prefer Typescript, compile time error checking, over linting.

In our next tip, we'll discuss the ViewModel concept.

Top comments (0)