Discover what TypeScript is, the problem it solves, and write your very first typed file.
Open this lesson in KodokonYou 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.
function addTax(price) {
return price + price * 0.2;
}
const total = addTax("100");
console.log(total); // "10020" instead of 120!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.
function addTax(price: number): number {
return price + price * 0.2;
}
const total = addTax(100);
console.log(total); // 120Now 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.
let firstName: string = "Sarah";
let age: number = 28;
console.log(firstName + " is " + age + " years old.");