AI Hints
Home›Angular Tutorial›Why TypeScript, Basic Types and Interfaces
Angular · Lesson 10 of 120

Why TypeScript

JavaScript with types.

⏱ 2 min read▶ Video at 10:56🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Angular apps are written in TypeScript. TypeScript is JavaScript, plus types. Types describe what kind of value something is, like a number, or a piece of text.

  • Angular uses TypeScript
  • JavaScript plus types
  • What kind of value

JavaScript or TypeScript

In plain JavaScript, a mistake like passing text instead of a number shows up only when the code runs. Maybe in front of a user. TypeScript checks the types before the code runs. So the mistake shows up in your editor, as you type.

JavaScript

  • No typesMistakes found while runningMaybe by users

TypeScript

  • Types on valuesMistakes found before runningIn your editor

A mistake caught early

Total takes a price, and a quantity, and both must be numbers. The first call is fine. The second passes the price as text, in quotes. Run it. TypeScript refuses to run it. It says, a string is not assignable to a parameter of type number, and gives the line, and column.

main.tstypescript
function total(price: number, quantity: number) {
  return price * quantity;
}

console.log(total(9.99, 2));
console.log(total("9.99", 2));
Output
main.ts(6,19): error TS2345: Argument of type 'string' is not assignable to parameter of
type 'number'.
Also uses _mode
ts

Fixed

We pass numbers, as promised. Run it. Both totals are printed. The type check passed, so the code ran.

main.tstypescript
function total(price: number, quantity: number) {
  return price * quantity;
}

console.log(total(9.99, 2));
console.log(total(4.5, 3));
Output
19.98
13.5
Also uses _mode
ts

How TypeScript runs

Browsers only understand JavaScript. So the TypeScript compiler checks the types, and then removes them. What's left is plain JavaScript, which runs anywhere. In Angular, the CLI does all of this for you.

keyvalue
Checktypes, before running
Thentypes are removed
Resultplain JavaScript
In Angularthe CLI does it

Summary

TypeScript adds types to JavaScript, and catches mistakes before the code runs. Next, the basic types.

Key takeaways
  • JavaScript + types
  • Checked before running
  • Compiled to JavaScript
Next up: Basic Types — string, number, boolean