TypeScript Everyday Types

TypeScript · 3 minute lesson

TypeScript adds static type checking to JavaScript. It can catch a mismatch while you work, such as passing a number where a function expects text. The code is compiled to JavaScript for execution, so type annotations help development without becoming automatic runtime validation.

Start with string, number, and boolean. Arrays can be written with a type followed by square brackets, such as string[]. TypeScript can infer many types from their initial values, so an annotation on every local variable is unnecessary. Explicit types are especially useful at function and data boundaries.

Use the editor feedback to understand a problem instead of silencing it immediately. The any type gives up useful checking and can let mistakes spread. Prefer a specific type when you know the value’s shape, and validate data from outside the program before relying on its contents.

Try the example

function lessonLabel(title: string, minutes: number): string {
  return `${title} · ${minutes} min`;
}

const topics: string[] = ["JavaScript", "React"];
console.log(lessonLabel(topics[0], 6));

Practice

Use the TypeScript Playground to run this example. Pass a string as the minutes argument and read the error. Correct the call, then add a boolean parameter that marks a lesson as completed.

Continue learning: Official documentation.