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

Basic Types

String, number, boolean.

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

Let's meet the types you'll use every day. They're simple, and there are only a few.

  • Everyday types
  • Simple
  • Only a few

The basic types

String is text, in quotes. Number is any number, whole, or with decimals. Boolean is true, or false. And any switches type checking off, so avoid it.

TypeValuesExample
stringtext"Dune"
numberany number9.99, 3
booleantrue or falsetrue
anyanything (avoid)no checks

Types on variables

A colon after the name gives the variable a type. Title is a string, price is a number, and in stock is a boolean. Copies has no type written. TypeScript works it out from the value, three, so it's a number. Run it. All four values print. And copies can grow by one, because it's a number.

main.tstypescript
let title: string = "Dune";
let price: number = 9.99;
let inStock: boolean = true;
let copies = 3;

console.log(title, price, inStock, copies);
copies = copies + 1;
console.log(`Copies now: ${copies}`);
Output
Dune 9.99 true 3
Copies now: 4
Also uses _mode
ts

Wrong types

Now we put text into price, and into copies. Both should be numbers. Run it. TypeScript reports both lines. Even copies is protected, although we never wrote its type.

main.tstypescript
let title: string = "Dune";
let price: number = 9.99;
let copies = 3;

price = "cheap";
copies = "three";
Output
main.ts(5,1): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(6,1): error TS2322: Type 'string' is not assignable to type 'number'.
Also uses _mode
ts

Types on functions

Parameters get types, the same way. The type after the brackets is what the function returns. Price with tax returns a number, and shout returns a string. Run it. Ten plus twenty percent is twelve. And shout returns SALE, with an exclamation mark.

main.tstypescript
function priceWithTax(price: number, rate: number): number {
  return Math.round(price * (1 + rate) * 100) / 100;
}

function shout(text: string): string {
  return text.toUpperCase() + "!";
}

console.log(priceWithTax(10, 0.2));
console.log(shout("sale"));
Output
12
SALE!
Also uses _mode
ts

Summary

Use string, number, and boolean, with a colon. TypeScript also works out types by itself. Next, interfaces.

Key takeaways
  • let price: number
  • Inferred types
  • Return types
Next up: Interfaces — the shape of an object