Basic Types

View saved

Use primitive annotations

Name the type after a colon. Inference often fills this in, but annotations document intent.

let title: string = "Courses";
let lessons: number = 18;
let published: boolean = true;
console.log(title, lessons, published);

Let TypeScript infer

When you initialize a variable, the compiler usually knows the type.

const score = 95;        // number
const label = "passed"; // string
console.log(typeof score, label);

Type arrays and objects

Arrays need an element type. Object shapes are clearer with interfaces (next lessons).

const tags: string[] = ["ts", "js"];
const point: { x: number; y: number } = { x: 10, y: 20 };
console.log(tags[0], point.x);

Avoid loose any for now

  • Prefer string, number, boolean, and arrays
  • Use null and undefined deliberately
  • Save any for rare escape hatches
  • Read compiler errors: they name the expected and actual types

Comments

One comment per signed-in account. Comments are saved with this page’s URL.