TypeScript in The Build Process 9 exercises
solution

Browsers Can't Understand TypeScript Syntax

The "Unexpected token" error shows up because browsers can't understand TypeScript syntax on their own.

In this case, the : string after message in the function declaration is not valid JavaScript:


const run = (message: string) => { // `: string` is not valid JavaScript!
cons

Loading solution

Transcript

00:00 The reason this wasn't working is that browsers can't understand TypeScript syntax itself. So we have a const run function here with message colon string. And this colon string is actually just not available in JavaScript. Browsers understand JavaScript, not TypeScript.

00:18 And so colon string, we can remove this if we want to, and then we end up with something that looks a bit more like JavaScript. But now TypeScript is going to yell at us because parameter message implicitly hasn't any type. So the way we get around this, basically in the solution, is we turn this TypeScript file into a JavaScript file.

00:36 And now inside JavaScript, this is perfectly valid JavaScript. And if we run hello here, we can see that in our console it's saying hello to us. I'll zoom in just a little touch here, just so you can see. If I change this to hello world, for instance, then I save, I refresh, and then it's hello world inside here. And of course, I've changed inside the index.html.

00:57 Instead of a .ts file, I've added .js instead. So when we create TypeScript files, we basically need to find a way to transpile them into JavaScript files, to turn them into JavaScript files, to basically run them in the browser. Because the browser, as well as various other things too, can only run JavaScript, not TypeScript.