Recently, I bumped into this interesting question as part of a discussion with a fellow developer. As a developer who uses TypeScript often (as part of creating various Angular projects), I was curious to understand what would happen if you try to run raw TypeScript code, such as the one below, directly in your browser without compiling (e.g. by putting it inside the <head> tag).
const sum = (a:number, b:number)=>a+b; sum();
Go ahead… try it.
If you try to execute it, you will likely encounter the same error as I did:
Uncaught SyntaxError: Unexpected token ':'
The reason for this is because all modern browsers follow the ECMAScript scripting-language specification, the same way that TypeScript follows it. However, they both follow it a different “pace”. Currently, TypeScript adopted features from far more modern versions of ECMAScript, whereas browsers like Google Chrome or Mozilla Firefox have barely adopted support for ECMAScript 2015 and partial support for ECMAScript 2016.
As a result, several features that are available in TypeScript are still not available in IE or Firefox due to their slower release cycle and slower adoption of ES in general.
How do I run TypeScript code inside the browser then?
Short answer, you can’t. You need to compile the .ts code into plain .js that is understood by all browsers and browser versions (e.g. IE6). You should acknowledge the fact that probably not all of your end users have the latest version of any given browser.
The good news is, that the framework that you are using (e.g. Angular, React) probably already has a good compiler that does the heavy lifting for you (e.g. Babel). A compiler’s job is to take the “modern” TypeScript that you write and convert it into “old school” .js files that work across all browsers and browser versions (optionally, including some polyfills),
A compiler may also create the so-called “.js.map files” that represent the links/relationship between the compiled .js code and the original .ts source code, allowing for easier debugging and breakpoint usage.