Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)

addTip(40, "5") returns 405 in JavaScript with no error. TypeScript stops it before it runs. Annotations, inference, interfaces, optional properties, unions with narrowing, generics vs any, and type vs interface, with real tsc messages.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Explain that tsc checks types before anything runs and then erases them
  • Write annotations where they help and rely on inference elsewhere
  • Describe object shapes with interfaces and optional properties, and read tsc errors
  • Narrow unions with typeof, in and a kind field, and keep types with generics instead of any

Before you start

  • JavaScript syntax: const, arrow functions, objects
  • npm and running tools with npx

TypeScript is JavaScript with types, and the whole idea fits in one line: the types are checked before your code runs, and then they're erased. Let's start with a tiny bug.

JavaScript finds the bug too late

// Plain JavaScript: nothing checks what goes in.
function addTip(bill, tip) {
  return bill + tip;
}

// The tip came from a text box, so it is text.
const total = addTip(40, "5");
console.log("Total to pay:", total);
console.log("Total times two:", total * 2);
Total to pay: 405
Total times two: 810

The tip came from a text box, so it's the string "5". 40 + "5" glues the two together into "405". Then * 2 turns that text back into a number, 810. There's no error at all, just a wrong answer that a user finds, not you.

TypeScript stops it before it runs

// The same function, with types on the way in and out.
function addTip(bill: number, tip: number): number {
  return bill + tip;
}

// tsc stops here: "5" is a string, not a number.
const total = addTip(40, "5");
console.log("Total to pay:", total);
npx tsc --noEmit tip.ts
tip.ts(7,26): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Now each parameter says what may go in: bill: number, tip: number, and : number after the brackets for what comes out. The 40 fits the first slot; the string "5" bounces off the second. tip.ts(7,26) means line 7, column 26, exactly where "5" starts, and TS2345 is the error number. tsc only read the file. Nothing ran, so the bug never reached a user.

Checked first, then erased

price.ts with types goes to tsc, which checks the types (0 errors) and writes price.js with the types removed. node runs price.js and prints Total to pay: 45. node never sees a type. price.ts addTip(bill: number, tip: number): number const tip: number = 5 tsc 1. check: 0 errors price.js "use strict"; addTip(bill, tip) const tip = 5 node 45 2. erase: tsc lifts every type off and writes plain JavaScript
Two separate steps: tsc checks the types, then removes them, and plain JavaScript runs.
// Types are checked first, then erased.
function addTip(bill: number, tip: number): number {
  return bill + tip;
}

const tip: number = 5;
const total = addTip(40, tip);
console.log("Total to pay:", total);

This is the file tsc wrote:

"use strict";
// Types are checked first, then erased.
function addTip(bill, tip) {
    return bill + tip;
}
const tip = 5;
const total = addTip(40, tip);
console.log("Total to pay:", total);
Total to pay: 45

Every : number is gone, and "use strict" was added because strict mode is on. Node never sees a single type. That has a practical consequence. The tool tsx runs a TypeScript file directly by stripping the types without checking them, so give it the broken tip.ts and it happily prints Total to pay: 405. Only tsc (or your editor, which runs the same checker) catches type mistakes, and only before the code runs.

Annotations and inference

// Annotation: you write the type after a colon.
const student: string = "Emma";
const scores: number[] = [82, 91, 67];

// Inference: no annotation, TypeScript works it out.
let best = 0;
const city = "Boston";

function average(values: number[]): number {
  const sum = values.reduce((a, v) => a + v, 0);
  return sum / values.length;
}

const avg = average(scores);
best = Math.max(...scores);

console.log(student, "from", city, "best:", best);
console.log("Average:", avg.toFixed(1));
Emma from Boston best: 91
Average: 80.0

student: string and scores: number[] are annotations: the type after a colon. let best = 0 has none, but TypeScript infers it; hover over it and the editor says let best: number. const city = "Boston" shows as const city: "Boston", the exact text, because a const never changes. And avg is inferred as number from average's return type.

Inferred types are guarded just the same. Add best = "high"; and tsc says Type 'string' is not assignable to type 'number'. Write types where they help a reader, such as parameters and return values, and let TypeScript infer the rest.

An interface is a shape

// An interface is the shape an object must have.
interface Task {
  id: number;
  title: string;
  done: boolean;
  owner?: string; // ? = optional: may be missing
}

const report: Task = {
  id: 1, title: "Report", done: true, owner: "Jack",
};
const trip: Task = {
  id: 2, title: "Trip", done: false,
};

function describe(task: Task): string {
  const owner = task.owner ?? "nobody";
  return `#${task.id} ${task.title} (${owner})`;
}

console.log(describe(report));
console.log(describe(trip));
#1 Report (Jack)
#2 Trip (nobody)

Task is the shape an object must have: four slots with a type each. report fills all four. trip has no owner, which is fine because owner? has a question mark, meaning optional.

Now two objects that don't fit:

// missing: done is not optional
const rent: Task = { id: 3, title: "Rent" };

// wrong type: done must be a boolean
const tax: Task = { id: 4, title: "Tax", done: "no" };
misfit.ts(10,7): error TS2741: Property 'done' is missing in type '{ id: number; title: string; }' but required in type 'Task'.
misfit.ts(13,42): error TS2322: Type 'string' is not assignable to type 'boolean'.

tsc names what's wrong and where: the missing property on line 10, and the string in a boolean slot at line 13, column 42.

Optional means maybe undefined

owner?: string really means "string or undefined". That's why describe uses task.owner ?? "nobody". Skip the check and write trip.owner.toUpperCase(), and tsc stops you:

error TS18048: 'trip.owner' is possibly 'undefined'.

Run it anyway with tsx and it crashes with TypeError: Cannot read properties of undefined (reading 'toUpperCase'). TypeScript makes you handle the missing case.

Unions, narrowed

// A union: id is ONE of these types at a time.
function show(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase(); // here: string
  }
  return "ORDER-" + id.toFixed(0); // here: number
}

console.log(show("ab12"));
console.log(show(7));
AB12
ORDER-7

string | number is a union: one of the two at a time. Inside the typeof id === "string" branch, TypeScript shrinks the type to string, so toUpperCase is allowed. After that branch returns, only number is left, so toFixed is allowed. That shrinking is called narrowing. Without a check, id.toUpperCase() fails:

error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

Unions of object shapes use a shared field to tell them apart:

// A discriminated union: "kind" tells the two apart.
type Card = { kind: "card"; last4: string };
type Cash = { kind: "cash"; amount: number };
type Payment = Card | Cash;

function receipt(p: Payment): string {
  if (p.kind === "card") {
    return "Card ending " + p.last4; // p: Card
  }
  return "Cash " + p.amount.toFixed(2); // p: Cash
}

function method(p: Payment): string {
  return "last4" in p ? "card" : "cash"; // in narrows
}

const paid: Payment = { kind: "cash", amount: 20 };
console.log(receipt(paid), method(paid));
console.log(receipt({ kind: "card", last4: "4242" }));
Cash 20.00 cash
Card ending 4242

Both shapes have kind with a different exact text. Checking p.kind === "card" narrows Payment to Card, so p.last4 is allowed; otherwise it's Cash and p.amount is allowed. "last4" in p narrows the same way by asking whether the property exists. A typo is caught too: receipt({ kind: "cheque", amount: 5 }) gives Type '"cheque"' is not assignable to type '"card" | "cash"'.

Generics: a type slot

// A generic: T is a type slot, filled in on each use.
interface Box<T> {
  value: T;
}

function box<T>(value: T): Box<T> {
  return { value };
}

const n = box(42); // T = number
const s = box("Sophie"); // T = string

console.log(n.value + 1);
console.log(s.value.toUpperCase());
43
SOPHIE

T is an empty type slot. Each call fills it from the value you pass: box(42) gives a Box<number>, box("Sophie") a Box<string>. TypeScript remembers, so n.value.toUpperCase() is caught with Property 'toUpperCase' does not exist on type 'number'. (At run time it would be TypeError: n.value.toUpperCase is not a function.)

Why not just use any?

// T follows the array you pass in; any forgets it.
function first<T>(items: T[]): T {
  return items[0];
}

function firstAny(items: any[]): any {
  return items[0];
}

const level = first([3, 1, 2]); // number
const who = first(["Emma", "Liam"]); // string
const loose = firstAny([3, 1, 2]); // any

console.log(level + 1, who.toUpperCase());
console.log(typeof loose);
4 EMMA
number

first keeps the type: level is a number and who is a string, so level.toUpperCase() is caught. firstAny throws the type away. loose is any, tsc says nothing about loose.toUpperCase(), and it crashes at run time with TypeError: loose.toUpperCase is not a function. A generic keeps the type of what you pass in; any forgets it and the mistake waits for run time.

type or interface?

// interface: an object shape, can be extended.
interface User {
  name: string;
}
interface Admin extends User {
  level: number;
}

// type: any type at all, joined with &.
type Id = string | number;
type Staff = User & { team: string };

const a: Admin = { name: "Emma", level: 2 };
const s: Staff = { name: "Liam", team: "Ops" };
const id: Id = 7;
console.log(a.name, s.team, id);
Emma Ops 7

Admin extends User gets name from User and adds level. Staff does the same idea with type and &. Only type can name a union like Id = string | number. The simple rule: interface for object shapes, especially ones you extend; type for unions and everything else.

Quick recap

IdeaRemember
tscchecks before anything runs; node never sees a type; tsx skips the check
Annotation / inferenceannotate parameters and returns, let the rest be inferred
interfacethe shape an object must have; errors come with line and column
owner?may be undefined; handle it with ?? or a check
Union + narrowingtypeof, in or a kind field shrinks the type
Generic <T>a type slot filled on each use; any forgets
type vs interfaceinterface for objects, type for unions

Python type hints are the closest match: str | int, Optional, TypedDict and generics, checked by a separate tool and ignored at run time. The difference is that TypeScript projects usually make the check part of the build, as tsc && vite build does in npm, packages and Vite. Later in the course, the TypeScript types for a React client are generated straight from a FastAPI spec: see generating a TypeScript client with Orval.

Try it yourself

Add a third payment shape, { kind: "voucher"; code: string }, to Payment. Run npx tsc --noEmit payments.ts and see whether receipt still compiles, then add a branch for it so every kind returns the right text.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 14 of 59

Previous
npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
Next post
Why React, JSX and Components: The Page as a Function of Data

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx

Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.

How a Web Page Works: HTML Tags, Elements and Attributes

A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.

Semantic HTML: header, nav, main, aside and footer as Page Landmarks

The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.

On this page

  • JavaScript finds the bug too late
  • TypeScript stops it before it runs
  • Checked first, then erased
  • Annotations and inference
  • An interface is a shape
  • Optional means maybe undefined
  • Unions, narrowed
  • Generics: a type slot
  • type or interface?
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.