Lesson 1 of 4 · 11 min · TypeScript fundamentals

TypeScript basics: types and interfaces

Covers: TypeScript 5.x with strict mode. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • What TypeScript is and how it relates to JavaScript
  • Basic types, annotations and type inference
  • Describe objects with interface and type
  • Optional and readonly properties, index signatures, unknown versus any
  • Type functions, arrays, tuples and enums-like unions

In simple words

TypeScript is JavaScript with labels. You add small notes saying what kind of value each variable and function expects, a number, some text, an order with a certain shape. Before the code ever runs, the TypeScript checker reads those notes and warns you about mistakes, such as passing text where a number is needed or reading a property that does not exist. Then it removes the labels and gives you ordinary JavaScript.

Words to know

  • Type: a description of what values a variable can hold.
  • Annotation: the : type you write to declare a type.
  • Inference: TypeScript working out a type from the value without being told.
  • Interface: a named description of the shape of an object.

What TypeScript is

TypeScript (TS) is a superset of JavaScript made by Microsoft: every valid JavaScript program is valid TypeScript, plus static types. The compiler (tsc) or a build tool (Vite, esbuild, SWC) checks types and erases them, producing plain JavaScript. Types exist only at development and build time; at run time there are none, so TypeScript does not validate data coming from the network (use a validation library such as Zod for that).

Why teams adopt it:

  • Catch bugs early: typos, wrong arguments, missing cases, null mistakes.
  • Better editor help: autocomplete, safe rename and refactoring, inline documentation.
  • Self-documenting code: types describe APIs and data shapes.
  • It is the default for most modern front-end (React, Angular) and Node.js work, so it is a common job requirement.

Recent Node.js versions can run .ts files directly by stripping erasable types, and tools such as tsx and ts-node do it too, but you still use tsc --noEmit (or your editor) for type checking.

Basic types and inference

let count: number = 3;
let title: string = "SQL";
let paid: boolean = true;
let nothing: null = null;
let missing: undefined = undefined;
let big: bigint = 123n;
let id: symbol = Symbol("id");

let city = "Pune";            // inferred as string: no annotation needed
city = 42;                    // Error: Type 'number' is not assignable to type 'string'

const rate = 0.18;            // inferred as the literal type 0.18 for a const
let skills: string[] = ["sql", "excel"];          // array of strings (also Array<string>)
let point: [number, number] = [17.38, 78.48];     // tuple: fixed length and types

Let TypeScript infer where it can; annotate function parameters and public function return types and empty containers (const items: Order[] = []). Over-annotating clutters the code.

Describing objects: interface and type

interface Customer {
  id: number;
  name: string;
  email?: string;                 // optional property
  readonly createdAt: Date;       // cannot be assigned after creation
}

type OrderStatus = "paid" | "pending" | "refunded";   // a union of literal types (like an enum)

type Order = {
  id: number;
  customer: Customer;
  amount: number;
  status: OrderStatus;
  tags: string[];
};

const order: Order = {
  id: 101,
  customer: { id: 1, name: "Asha", createdAt: new Date() },
  amount: 1200,
  status: "paid",
  tags: [],
};

order.status = "shipped";         // Error: not assignable to type OrderStatus
order.customer.createdAt = new Date();   // Error: read-only property
order.customer.email.toLowerCase();       // Error: 'email' is possibly undefined (strict mode)

interface or type? Both describe object shapes and are largely interchangeable. Guidance used by many teams:

interface type
Object shapes yes yes
Extend interface B extends A (and declaration merging) type B = A & { ... } (intersection)
Unions, tuples, primitives, mapped and conditional types no yes
Same name declared twice merges yes no (an error)

A simple rule: use interface for object shapes that are public APIs or that may be extended (classes can implements them), and type for everything else (unions, tuples, utility combinations). Whichever you pick, be consistent.

interface Person { name: string }
interface Student extends Person { grade: number }

type Id = number | string;
type Pair<T> = [T, T];

Index signatures and Record

interface Scores { [subject: string]: number }                // any string key maps to a number
const marks: Scores = { maths: 92, english: 85 };

const prices: Record<string, number> = { pen: 10, book: 120 };    // Record<K, V>: the same idea

With the noUncheckedIndexedAccess option, reading marks.maths has type number | undefined, forcing you to handle a missing key.

any, unknown and never

  • any turns off type checking for a value: it spreads silently and defeats TypeScript. Avoid it; if you must, comment why.
  • unknown is the safe "I do not know the type yet": you must check it before using it.
  • never is the type of something that cannot happen (a function that always throws, an impossible branch).
function parse(text: string): unknown {
  return JSON.parse(text);
}
const data = parse('{"id": 1}');
data.id;                                   // Error: 'data' is of type 'unknown'
if (typeof data === "object" && data !== null && "id" in data) {
  console.log((data as { id: number }).id);     // narrowed, then a cautious assertion
}

Use unknown for values from JSON.parse, catch clauses (catch (error) is unknown in strict mode) and external input, and validate them (a type guard or a Zod schema) before use.

Functions

function total(price: number, quantity = 1): number {
  return price * quantity;
}

const greet = (name: string, title?: string): string =>
  title ? `${title} ${name}` : name;

function log(message: string): void {                     // returns nothing useful
  console.log(message);
}

type Handler = (event: MouseEvent) => void;               // a function type
const onClick: Handler = (event) => console.log(event.clientX);

function connect(host: string, options: { port?: number; ssl?: boolean } = {}): void { /* ... */ }
  • Parameters must be typed (or inferred in callbacks whose type is known).
  • Optional parameters use ? or a default; rest parameters: (...numbers: number[]).
  • Overloads allow several call signatures for one function, rarely needed.
  • async functions return Promise<T>: async function getOrder(id: number): Promise<Order> { ... }.

Type assertions and `satisfies`

const input = document.getElementById("q") as HTMLInputElement;   // "trust me": no runtime check
const config = { port: 8080, host: "localhost" } satisfies { port: number; host: string };

An assertion (as) overrides the checker and can lie; use it sparingly (for DOM elements and after real checks), and never as any to silence errors. satisfies (TS 4.9) checks that a value matches a type without widening it, keeping precise inferred types. as const makes literals read-only and narrow: const roles = ["admin", "user"] as const; has type readonly ["admin", "user"].

Enums versus literal unions

TypeScript has enum, which generates JavaScript code; most teams now prefer string literal unions (type Status = "paid" | "pending") or an as const object, which have no run-time cost and work with erasable-syntax-only setups:

const Status = { Paid: "paid", Pending: "pending" } as const;
type Status = (typeof Status)[keyof typeof Status];       // "paid" | "pending"

Classes

TypeScript adds access modifiers and shorthand to classes:

class Account {
  constructor(public readonly owner: string, private balance = 0) {}     // parameter properties
  deposit(amount: number): void { this.balance += amount; }
}

(Parameter properties and enum are not "erasable" syntax, so projects that run TypeScript by stripping types avoid them.) Note that private is a compile-time check only; use #field for real run-time privacy.

Strict mode

Turn on "strict": true in tsconfig.json (the next lessons). It enables the checks that make TypeScript worthwhile: strictNullChecks (no null or undefined unless the type says so), noImplicitAny (no silent any), strictFunctionTypes and more. New projects should always use it; migrate old JavaScript to TypeScript gradually (allowJs, rename files one by one).

Common mistakes

  • Using any to make errors disappear.
  • Overusing as assertions, lying to the compiler.
  • Believing types validate run-time data from APIs and forms.
  • Annotating everything instead of trusting inference.
  • Turning off strict.
  • Using Object or Function types instead of precise shapes.
  • Making every property optional because the data is "sometimes missing" instead of modelling it properly.

Try it yourself

  1. Install TypeScript (npm install -D typescript), create tsconfig.json with "strict": true (npx tsc --init) and write a small Order interface and a function that totals orders; run npx tsc --noEmit.
  2. Introduce three deliberate type errors and read each message.
  3. Replace an enum with a union of string literals.
  4. Parse JSON into unknown and narrow it safely with checks.
  5. Write a typed async function that fetches an order and returns Promise<Order>.

Check yourself

Does TypeScript check types at run time?

No. Types are checked at build time and erased; run-time data (such as API responses) needs separate validation.

What is the difference between any and unknown?

any disables type checking; unknown is a safe type that requires you to narrow or check the value before using it.

When would you choose type instead of interface?

For unions, tuples, mapped or conditional types and aliases of primitives; interface is common for extensible object shapes.

What does strict: true enable?

A group of strict checks including strictNullChecks and noImplicitAny, which catch null mistakes and untyped values.

Interview questions

What is TypeScript and why use it?

A typed superset of JavaScript that compiles to JavaScript; it catches errors at build time, improves tooling and documents code, which pays off in larger codebases.

Interface versus type alias: what are the differences?

Interfaces describe object shapes, can be extended and merged, and suit classes; type aliases can also name unions, tuples and computed types but cannot merge. Both work for most object shapes.

What is type inference?

The compiler deducing types from values and context (let n = 5 is number), so you annotate mainly function parameters, return types where helpful and empty collections.

Summary

  • TypeScript adds static types to JavaScript; they are checked at build time and erased.
  • Annotate parameters and public APIs, let inference do the rest; use interfaces and type aliases for shapes.
  • Prefer unknown to any, literal unions to enums, satisfies and as const for precise types.
  • Always use strict; validate external data at run time.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on TypeScript for JavaScript developers for Frontend Developer and scores every answer, with what to fix.