DEV Community

Cover image for Future Javascript: Types may finally be coming to Javascript
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

Future Javascript: Types may finally be coming to Javascript

With the promotion of Type Annotations to Proposal Level 1 Stage, Javascript is one step closer to being a more strongly typed language. Let's dive into what the changes will mean for Javascript.

Types in Javascript

Javascript is dynamically typed. That means that it figures out the type of something by where it appears. For example:

let x = 1; // typeof "number"
let y = "1"; // typeof "string"
Enter fullscreen mode Exit fullscreen mode

In complicated application and systems, this is a huge weakness. Applications can fall over for the smallest of things - such as your API returning "false" instead of false.

That means we have to sometimes bullet proof our code by doing silly things like this, especially in instances where we don't have control over a piece of software sending back wonky types:

if(x === true || x === "true") {
    // this is true
}
Enter fullscreen mode Exit fullscreen mode

This is a huge annoyance for dyed in the wool software engineers, but for beginners, Javascript is a gift. Javascript makes it so easy to write quite complicated things in a simple way. If your code is wrong, Javascript usually finds a way to make it work. Most Javascript developers find that the flexibility they love at the start, soon becomes painful as they become more competent in the language.

For these reasons, there has never been a strong push to make Javascript a typed language, with hard rules. The accessibility of Javascript is one of its great traits, and adding types would not only make it harder for beginners, but also potentially break a lot of the existing web technologies built on untyped Javascript.

As such, optional packages were developed instead - TypeScript and Flow being two of the best known. These take Javascript and turn it into a language with strongly declared types.

Enter: Javascript Types

The new type annotations proposal tries to find a middle ground, so Javascript can remain accessible, but allow for advanced features like types more easily.

In some ways, this was an inevitability. Strong types consistently come out on top of the most requested developer features for Javascript:

Most requested Javascript features

How Type Annotations will Work

To be clear, type annotations will not make Javascript a strongly typed language. Instead, they let Javascript work with types. What that means is, if you add types to Javascript once this specification reaches an implementation stage, they will simply be ignored. Should you compile it with Typescript, though, the types will work as normal.

If you've used TypeScript before, then, you'll be familiar with how type annotations look. For example, defining a type for a variable looks like this:

let x:string = "String";
let x:number = 5;
Enter fullscreen mode Exit fullscreen mode

How Javascript would work after type annotations

Let's say you write a piece of code that looks like this:

let x = "String";
console.log(x);
Enter fullscreen mode Exit fullscreen mode

Later down the line, you decide you want to add types. Instead of having to compile it with TypeScript, with type annotations we can simply add the types to our Javascript file:

let x:string = "String";
console.log(x);
Enter fullscreen mode Exit fullscreen mode

In this case, :string is simply ignored by Javascript - meaning it remains compatible with untyped Javascript, and type bundles like TypeScript. That means you can build it with TypeScript, but you can also just run it as a normal .js file. Types in a vanilla Javascript file are ultimately comments.

Other Examples of Types in Type Annotations

The general roster of types that you'd expect can be found in type annotations. For example -

interfaces:

interface Name {
    firstName: string,
    lastName: string
}
Enter fullscreen mode Exit fullscreen mode

union types:

function test(x: string | number) {
    console.log(x);
}
Enter fullscreen mode Exit fullscreen mode

generic types:

type Test<T> = T[];
let x:Test<number> = [ 1, 2, 3, 4 ];
Enter fullscreen mode Exit fullscreen mode

Rationale behind Type Annotations

The main rationale is that as browser development has become more streamline, and backend Javascript ecosystems like Deno and Node.JS have become more popular, there have been opportunities for Javascript to move to less and less build steps. The big change comes with TypeScript, where to run a TypeScript file, we need to build it back to Javascript. This is obviously a time consuming and sometimes onerous step for developers, and definitely limits efficiency.

One of the main draws to type annotations in TypeScript is that it removes another build step. Native TypeScript can be run in the browser without the need to convert it back to Javascript, greatly optimising the developer experience.

As well, this type annotation acts give a standard base to type definitions in Javascript. By standardising the most agreed upon parts of types in Javascript, it ensures consistency across all type compilers, making things easier for developers.

Conclusion

In conclusion, types are coming to Javascript, but perhaps not in the way people envisioned. Javascript will remain a dynamically typed language, but it will accept type declarations natively. This specification is still stage 1, so a lot may change - but it's an exciting time for Javascript to take its first step into a more strongly typed world.

Latest comments (25)

Collapse
 
hellojavascriptinfo profile image
HelloJavaScript.info

First I would like to address the elephant in the comments below. Most people who write plain old Vanilla JavaScript have nothing to worry about when it comes to a type system in the browser. You can remain calm about these changes in the browser. Type systems are useful when you are in development mode. You will not see types if you don't use them and if you do you have a much better developer experience. Here is my rule when I am developing an application. If I am working with a team then use types and if I am working by myself it's up to me. For those of you who don't like TypeScript then you should stick to what you know. However, the future use of type systems will become part of your day to day job if you work with large team. Get use to it...

Collapse
 
pengeszikra profile image
Peter Vivo

I use hybrid TS / JS application, so if JS also use other type declaration that is will be really confusing. By the way TS type definitions not by accident complex for handle ( near ) all type definition. I think that complexity handle in real time just slow down the browsers.

Collapse
 
leob profile image
leob

So they're sort of duplicating the work done by Typescript, or what? Now we'll have even more confusion and fragmentation (some people using full TS, others use "JS-the-poor-man's-TS"), or am I misunderstanding things?

 
ivan_jrmc profile image
Ivan Jeremic

If you can do everything in JS there is no need for TS to exist. (Which I hope will happen)

Thread Thread
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

Well, you can't. Or atleast not yet. Let's see what the future holds.

Thread Thread
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

Time shall tell!

Collapse
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

Typescript has come to stay.

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

Nor really the people behind TS made this proposal.

Thread Thread
 
emmanuelthecoder profile image
Emmanuel Aiyenigba

I know. Types coming to JS is never the end of TS.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Those type annotations have no place being processed by the JS engine. That belongs in a browser extension and nowhere else

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

They are not being processed, the engine looks at them same as it looks at // comments which is good because we don't need a transpile step.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

So what on earth is the point of them? Or a proposal? Or anything? If they are effectively just 'comments'?

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic

The same point TypeScript has, Typescript Types are also not used in the JS Engine they help you while Developing.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

To make the engine ignore the type annotations as if they were comments will require changes to the JS engine (yes, processing). These are changes that only benefit TS developers whilst developing. Adding extra load to the JS engine just for this purpose is plain stupid.

This belongs in a browser extension - which would essentially just be moving a compile-like step into the browser instead of it happening server side.

Let's not let the overblown tooling and complexity that has infected the JS development process in the name of "developer convenience" start dragging down the client side too.

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic

You clearly have no idea, browser extension wtf? LoL

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Yeah - a browser extension to strip out the type annotations before giving the JS to the JS engine. Not sure if feasible, but a way better idea than putting this crap into the core of the engine.

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic

Are you serious? How do you want to tell millions of people, "Hey please install this Browser Extension" if you really want to strip it out the place to do it is with a build script but not an extension in the browser lol.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

So now you don't want browsers to accept this syntax? Make your mind up.

If TS developers want this syntax to be accepted in the browser as an aid to their development process (bear in mind that these annotations would be stripped in production code as it makes no sense to bloat the bundles with code that the engine will ignore) then it's not really a big issue for them to have a browser extension to allow it. The majority of people using the browsers are not developers, and this has no benefit to them whatsoever. There are already browser extensions to assist with React development and many other things - how would this be any different?

Unless JS actually implements type hinting using this syntax, then there really is no point modifying the JS engines to allow and ignore it, just to make the lives of a minority of browser users' lives easier.

Thread Thread
 
smpnjn profile image
Johnny Simpson

The idea is that by putting types as comments into Javascript, we create a base for all strongly typed Javascript packages like TypeScript and Flow. That way simple types can be standardised. That's useful in itself, and also acts as a stepping stone to a strongly typed standard version of Javascript.

If we did that in a browser extension, then Javascript files would be invalid if we wrote them with annotated types and didn't have the extension installed.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

If we did that in a browser extension, then Javascript files would be invalid if we wrote them with annotated types and didn't have the extension installed.

Yes, but this wouldn't be an issue as only developers would be sending this kind of code while they were developing, and they would have the extension installed. Production code would be back to normal JS. Presumably, you'd want to strip comments out of production code anyway... so types in comments, or types as TS syntax really aren't that much different. Swings and roundabouts.

Back to my original question - why the proposal if they're just going to be put in as comments? It would be farcical to suggest any actual implementation of type hinting in JavaScript would have the hints in comments. Also, wouldn't suddenly switching to putting types in comments (instead of the existing TS syntax) really piss off a whole load of TS developers? You'll end up with a mess - some devs doing it the old way, some day it in comments, or some unholy mix of the two.

Thread Thread
 
smpnjn profile image
Johnny Simpson

It's simply because adding types to Javascript wholesale would break half of the internet. It would be a massive language change and would affect many components of Javascript. This change is a slow step in that direction, but it's non-committal. This can be implemented with no damage to already existing websites, and then tc39 can decide how to proceed from there. It's incremental steps.

The main benefit to this is of course it reduces the need to compile. Currently TypeScript requires you to compile your files into standard Javascript so they can be run in the browser or on a Node.JS/Deno server. With this, there is no need to compile anymore. TypeScript files are valid Javascript, the types are just ignored.

Therefore TypeScript can still enforce its rules and checks, and take out the compile step - meaning a faster overall development time for developers.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

So the proposed change really affects TS then (making the compiler read type info from comments) - complicating development further (as mentioned above)? Honestly, all this faffing around would be gone if developers just accepted JS for the language it is, and work with it instead of fighting against it. I've been coding for 38 years (26 professionally) and - quite honestly, when I first came to JavaScript it was a breath of fresh air after working within the straitjacket of strongly typed languages.

Thread Thread
 
smpnjn profile image
Johnny Simpson

That's why it's annotated, and not enforced. Annotated types mean you can still write your Javascript with types, and it'll be valid Javascript, or you can write it without types, to get the flexibility you describe.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

So much yak shaving just to avoid adapting your mindset to using a language that doesn't have strict typing. I'll never understand it.

This proposal just feels like TS creators trying to dig themselves out of a hole that they created for themselves

Thread Thread
 
mateusmento profile image
Mateus Sarmento • Edited

Dude you seem a bit stoned reading from your comments. But I don't understand your unnecessary complain with a proposal for types in javascript. To be honest I agree with you to say that the type annotations would not be meaningful for the javascript language itself if "treated like comments", which actually is my complain here. Having type check in runtime would open the doors for something like multiple dispatch for functions which would be wonderful for implementing ad-hoc polymorphism and being able to simply overload functions... I really think you are either being unreasonable or just really stoned. This browser extension thing was hilarious...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.