TypeScript, lesson 1
TypeScript is JavaScript with types added on top. You write ordinary JavaScript, and you may also say what kind of value each variable and function works with. A type checker reads those notes and warns you about mistakes, such as passing text where a number is expected, before the program ever runs.
In this course your code runs on Deno, a runtime that understands TypeScript directly. You do not need a separate compile step: Deno removes the type annotations and runs the resulting JavaScript. There is no web page here. Your program prints text, and that text is the result.
The tool for printing is console.log(). It writes a value followed by a line break to
standard output (stdout), which is where the tests read your answer.
console.log("Hello, World!");
console.log("TypeScript runs one statement at a time.");Text in quotes is a string. Double quotes, single quotes and backticks all make strings; backticks have extra powers you will meet in the next lesson. End statements with a semicolon.
console.log() accepts several values separated by commas and prints them on one line with a
space between each pair:
To join strings without a space, use +: "snow" + "ball" is "snowball".
Comments are notes for people; Deno ignores them.
Here is the first piece of real TypeScript: a variable with a type annotation.
: string says that planet holds text. If you later wrote const planet: string = 42;, the
editor would underline it as an error. However, deno run (which the runner uses) does not
type-check by default: it strips the types and runs the code. So a type error will not stop
your program here; it is your editor's red squiggles that catch it. In real projects you run
deno check to make the checker part of your workflow. Treat every type error as a bug, even
when the program appears to work.
Deno reads your file from top to bottom and runs each statement in order. If something fails at run time, for example calling a function that does not exist, Deno stops and prints an error message with the file and line number to standard error (stderr), which is separate from your normal output.
2 exercises to try what you just read.
console.log("Score:", 7, "of", 10); // Score: 7 of 10
console.log(6 * 7); // 42 (the expression is computed first)
console.log(); // an empty line// A line comment runs to the end of the line.
console.log("This runs"); // it can follow code
/* A block comment
can span several lines. */const planet: string = "Mars";
console.log("Hello from", planet);console.log("first");
consle.log("second"); // typo: ReferenceError, the program stops here
console.log("never printed");Hello, World!
I am learning TypeScript.=== ARES IV ===
Destination: Mars
Crew: 3 pilots + 2 scientists
Total crew: 5