Kodokon kodokon.com

Why TypeScript, your first typed file

Discover what TypeScript is, the problem it solves, and write your very first typed file.

6 min · 3 questions

Open this lesson in Kodokon

You already know JavaScript, the language that makes web pages interactive. TypeScript is an extension of JavaScript: any valid JavaScript code is also TypeScript code. Its big addition is types. A type describes the nature of a value: a text, a number, a true or false... By stating the type of your variables, you let the computer check your code before running it.

Why is this useful? In JavaScript, nothing stops you from passing a text where a number was expected. The program still runs... and produces an absurd result, often discovered much later. Look at this example: the function expects a price as a number, but receives a text.

JAVASCRIPT
function addTax(price) {
  return price + price * 0.2;
}

const total = addTax("100");
console.log(total); // "10020" instead of 120!
In JavaScript, this mistake goes completely unnoticed.

With TypeScript, you add a type annotation: a colon followed by the type, right after the name of a parameter or variable. TypeScript code is then compiled, meaning translated into plain JavaScript by a tool called the compiler (tsc). It is during this step that type errors are detected and reported.

TYPESCRIPT
function addTax(price: number): number {
  return price + price * 0.2;
}

const total = addTax(100);
console.log(total); // 120
Here, writing addTax("100") would be rejected before execution.

Now let's write your first typed file. A TypeScript file uses the .ts extension instead of .js. Inside, you write regular JavaScript, enriched with type annotations.

TYPESCRIPT
let firstName: string = "Sarah";
let age: number = 28;

console.log(firstName + " is " + age + " years old.");
Your first file: hello.ts

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is TypeScript in relation to JavaScript?
    • A completely different language from JavaScript
    • An extension of JavaScript that adds types
    • A tool to make JavaScript faster
    • A web browser
  2. What happens when you compile a .ts file?
    • It is transformed into a plain JavaScript file
    • It is executed directly by the browser
    • It is converted into an HTML page
  3. What does the annotation in let age: number mean?
    • The variable age is always zero
    • The variable age can only hold numbers
    • The variable age is a text
    • The variable age is optional