Courses / Frontend System Design, with JavaScript Foundations / Chapter 5
Module 2 · JavaScript Foundations · Chapter 5 of 21
TypeScript for Frontend Engineers
Builds on Values, Coercion, Scope and Closures, this, Prototypes and Classes and Promises, Async Code and the Browser Event Loop. Next up: The DOM, Events and Observers.
Part 1 · Structural typing and literal types
Shapes, not names
Many frontend codebases are written in TypeScript, because its types catch a whole class of mistakes before a page loads. Every example here was checked with TypeScript 7.0.2.
TypeScript describes the shape of a value, not the name of the type it came from. A value fits a type when it has every member the type asks for, whatever else it carries. This is called structural typing, and it differs from nominal typing, where a value fits only if it was declared as that exact type. JavaScript code passes plain objects around, so a structural system fits it naturally.
The function below needs a Point. The variable sample was never declared as a Point, and it has an extra label member, yet it is accepted because it has numeric x and y.
type Point = { x: number; y: number } function norm(p: Point): number { return Math.hypot(p.x, p.y) } const sample = { x: 3, y: 4, label: 'corner' } console.log(norm(sample)) norm({ x: 3, y: 4, label: 'corner' })
The direct call on the last line is different. An object literal written right at the call site gets an excess property check: the compiler assumes a member nobody asked for is a typo. The check applies only to fresh literals, which is why the first call passes and the last one fails.
t1a.ts(10,20): error TS2353: Object literal may only specify known properties, and 'label' does not exist in type 'Point'.
Output (tsc 7.0.2, long lines wrapped)
The compiler reports an error, but the file still runs. Node strips the annotations and executes what remains, because types are erased before the program runs.
5Output (Node 24)
type and interface
Two keywords describe object shapes. A type alias gives a name to any type, including unions and tuples. An interface describes an object shape and can be extended with extends. The practical difference is declaration merging: two interfaces with the same name in one scope become a single interface, while two type aliases with the same name are an error.
interface Settings { theme: 'light' | 'dark' } interface Settings { locale: string } const s: Settings = { theme: 'dark' } type Alias = { a: number } type Alias = { b: number }
t1b.ts(4,7): error TS2741: Property 'locale' is missing in type '{ theme: "dark"; }' but required in type 'Settings'. t1b.ts(6,6): error TS2300: Duplicate identifier 'Alias'. t1b.ts(7,6): error TS2300: Duplicate identifier 'Alias'.
Output (tsc 7.0.2, long lines wrapped)
The first error shows the merge: Settings now needs both members, so the object with only theme is rejected. Merging is how libraries let you add members to a global interface such as Window. In application code it is more often a surprise than a feature.
| Need | Use |
|---|---|
| A union, tuple or mapped type | type |
| An object shape that other shapes extend | interface or type |
| Adding members to a library interface | interface (merging) |
| Preventing accidental merging | type |
Pick one style for object shapes and keep to it across a codebase. Either works for the examples in this course, so they use type unless merging is the point.
Literal types and widening
A literal type is a type with exactly one value, such as 'GET' or 3. A union of literal types describes a fixed set of choices, which is how you type an HTTP method or a status. The compiler decides whether a variable gets a literal type or a wider one by asking if it can change. A const binding cannot be reassigned, so const kind = 'idle' has the type 'idle'. A let can be reassigned, so let mode = 'idle' is widened to string.
Object properties are mutable, so they widen even inside a const object. That bites when you pass a property to a function that wants a literal union.
type Method = 'GET' | 'POST' function send(method: Method, url: string): string { return method + ' ' + url } const loose = { method: 'GET' } const fixed = { method: 'GET' } as const console.log(send(fixed.method, '/cart')) send(loose.method, '/cart')
t1c.ts(11,6): error TS2345: Argument of type 'string' is not assignable to parameter of type 'Method'.
Output (tsc 7.0.2, long lines wrapped)
The as const assertion tells the compiler to keep the narrowest type and mark everything read-only. fixed.method is the literal 'GET', so the first call passes. loose.method is a plain string, so the second fails.
You can prove these inferred types with a small helper that compares two types for exact equality. Expect only accepts true, so a wrong claim is a compile error.
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false type Expect<T extends true> = T let mode = 'idle' const kind = 'idle' const loose = { method: 'GET' } const fixed = { method: 'GET' } as const const list = ['a', 'b'] const frozen = ['a', 'b'] as const type Checks = [ Expect<Equal<typeof mode, string>>, Expect<Equal<typeof kind, 'idle'>>, Expect<Equal<typeof loose.method, string>>, Expect<Equal<typeof fixed.method, 'GET'>>, Expect<Equal<typeof list, string[]>>, Expect<Equal<typeof frozen, readonly ['a', 'b']>>, ]
The Equal helper is a common idiom; copy it into a types test file.
no errors reported
Output (tsc 7.0.2, long lines wrapped)
No errors means all six claims hold, including that as const on an array gives a read-only tuple of literals.
satisfies
A type annotation on a variable replaces the inferred type with the annotation. The satisfies operator does something different: it checks that a value fits a type and keeps the narrower inferred type.
type Colour = string | number[] const annotated: Record<string, Colour> = { green: '#0f0', red: [255, 0, 0], } annotated.green.toUpperCase() const checked = { green: '#0f0', red: [255, 0, 0], } satisfies Record<string, Colour> console.log(checked.green.toUpperCase(), checked.red.length) type Tab = 'home' | 'cart' const labels = { home: 'Home', chart: 'Cart', } satisfies Record<Tab, string>
t1e.ts(7,17): error TS2339: Property 'toUpperCase' does not exist on type 'Colour'. Property 'toUpperCase' does not exist on type 'number[]'. t1e.ts(18,3): error TS2561: Object literal may only specify known properties, but 'chart' does not exist in type 'Record<Tab, string>'. Did you mean to write 'cart'?
Output (tsc 7.0.2, long lines wrapped)
With the annotation, annotated.green is the whole Colour union, so calling a string method on it fails. With satisfies, checked.green is still a string and checked.red is still an array, so both calls work and the program prints the result. The last object shows the other benefit: a misspelt key is caught against Record<Tab, string>, and the message even suggests the right name.
Use an annotation when you want the declared type to be the contract. Use satisfies for a configuration object where you want checking and also want each entry to keep its own type.
#0F0 3Output (Node 24)
Why does norm(sample) compile when sample has an extra label member, but the same object written inside the call does not?
- Structural typing accepts any value that has the required members.
- Excess property checks run only on fresh object literals, where an unknown key is probably a typo.
What is the type of let mode = 'idle' and of const kind = 'idle'?
modeis widened tostringbecause it can be reassigned.
Part 2 · Unions and narrowing
Why unions need narrowing
A union type such as string | number says a value is one of several types. Frontend data is full of them: an input value that may be missing, a response that is either data or an error, a payment that is idle, pending or paid. TypeScript only lets you use members that exist on every part of the union, so you must first find out which part you hold.
That step is narrowing: the compiler follows your checks and refines the type inside each branch. The most common checks are typeof for primitives, in for a property, instanceof for a class, equality, and truthiness.
function pad(value: string | number): string { return value.toFixed(2) }
t2e.ts(2,16): error TS2339: Property 'toFixed' does not exist on type 'string | number'. Property 'toFixed' does not exist on type 'string'.
Output (tsc 7.0.2, long lines wrapped)
The error names the cause. toFixed exists on number but not on string, and the compiler cannot tell which one you have. After a typeof value === 'number' check it can.
type Circle = { radius: number } type Rect = { w: number; h: number } function area(shape: Circle | Rect): number { if ('radius' in shape) return Math.PI * shape.radius ** 2 return shape.w * shape.h } function year(d: Date | string): string { return d instanceof Date ? String(d.getFullYear()) : d.slice(0, 4) } function isDefined<T>(x: T | null | undefined): x is T { return x != null } const raw = [1, null, 3, undefined] const clean = raw.filter(isDefined) console.log(area({ radius: 2 }).toFixed(2), area({ w: 2, h: 5 })) console.log(year(new Date(2026, 10, 22)), year('2027-01-23')) console.log(clean)
12.57 10 2026 2027 [ 1, 3 ]
Output (Node 24)
Each function narrows with a different check. area uses in to tell a circle from a rectangle. year uses instanceof. The last helper is a type predicate: the return type x is T tells the compiler that when the function returns true, the argument has type T. Passing it to filter is how you remove null and undefined from an array and get a clean number[] back.
Discriminated unions
A discriminated union is a union of object types that share one property, the discriminant, whose type is a different literal in each member. Checking that property narrows the whole object. This is the standard way to model state that has different data in each stage.
A payment is a good example. An idle payment has nothing. A pending one has a start time. A paid one has a receipt. A failed one has a reason. A single object with every field optional would allow nonsense such as a paid payment with no receipt. The union rules it out.
type Payment = | { status: 'idle' } | { status: 'paid'; receipt: string } function receipt(p: Payment): string { return p.receipt }
t2d.ts(6,12): error TS2339: Property 'receipt' does not exist on type 'Payment'. Property 'receipt' does not exist on type '{ status: "idle"; }'.
Output (tsc 7.0.2, long lines wrapped)
The compiler refuses p.receipt because the idle member has no such property. Reading it is only legal once a check on status has narrowed the union to the paid member.
Exhaustive checks with never
The type never has no values. It appears when narrowing has ruled out every member of a union. You can use that: in the last branch of a switch over the discriminant, the leftover type should be never, and passing it to a function that takes never makes the compiler verify it.
type Payment = | { status: 'idle' } | { status: 'pending'; startedAt: number } | { status: 'paid'; receipt: string } | { status: 'failed'; reason: string } function assertNever(x: never): never { throw new Error('unhandled: ' + JSON.stringify(x)) } function label(p: Payment): string { switch (p.status) { case 'idle': return 'Pay now' case 'pending': return 'Waiting since ' + p.startedAt case 'paid': return 'Receipt ' + p.receipt case 'failed': return 'Failed: ' + p.reason default: return assertNever(p) } } console.log(label({ status: 'idle' })) console.log(label({ status: 'paid', receipt: 'R-1042' })) console.log(label({ status: 'failed', reason: 'card declined' }))
Pay now
Receipt R-1042
Failed: card declinedOutput (Node 24)
Now the product grows a refund state. Adding one member to the union, and nothing else, gives this.
type Payment = | { status: 'idle' } | { status: 'pending'; startedAt: number } | { status: 'paid'; receipt: string } | { status: 'failed'; reason: string } | { status: 'refunded'; amount: number }
Same file with one more union member; only the top is shown.
t2c.ts(23,26): error TS2345: Argument of type '{ status: "refunded"; amount: number; }' is not assignable to parameter of type 'never'.
Output (tsc 7.0.2, long lines wrapped)
The default branch now receives a refunded payment, which is not never, so the call fails and the compiler points at the function that forgot the case. At runtime the same line throws, so a missed case is caught in both places.
Watch for what the compiler knows about the payment in each state
Read it as steps
Part 3 · Generics
Types that take parameters
A generic is a function or type that takes a type as a parameter, written in angle brackets. It lets one definition work for many types while keeping the link between input and output. Without generics you would pick between a loose any and one copy of the function per type.
first below returns the first item of an array. The type parameter T is filled in from the argument: pass a Product[] and the result is Product | undefined. The | undefined is honest, because an empty array has no first item.
type Product = { id: number; title: string; paise: number } const products: Product[] = [ { id: 1, title: 'Steel bottle', paise: 49900 }, { id: 2, title: 'Notebook', paise: 12000 }, ] function first<T>(items: T[]): T | undefined { return items[0] } function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]) } function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b } console.log(first(products)?.title) console.log(pluck(products, 'paise')) console.log(longest('ab', 'abc'), longest([1, 2, 3], [4]))
Steel bottle [ 49900, 12000 ] abc [ 1, 2, 3 ]
Output (Node 24)
T is inferred from the arguments, so callers rarely write it. You can also pass it explicitly, as in first<Product>(products), which helps when inference has nothing to work from.
Generic types
Type aliases and interfaces take parameters too. A generic type is a template for a family of types, and it is the usual way to describe a result that can succeed or fail without throwing. Result<T> below is a discriminated union, so the narrowing from the previous lesson applies to it, and T fills in the type of the success value.
type Result<T> = { ok: true; value: T } | { ok: false; error: string } function parseQty(text: string): Result<number> { const n = Number(text) if (Number.isInteger(n) && n > 0) return { ok: true, value: n } return { ok: false, error: `"${text}" is not a quantity` } } for (const text of ['3', '0', 'two']) { const r = parseQty(text) console.log(r.ok ? r.value * 2 : r.error) }
6 "0" is not a quantity "two" is not a quantity
Output (Node 24)
parseQty returns either a value or a message, and the caller must check r.ok before using either. Inside the true branch r.value is a number, and inside the false branch r.error is a string. The same Result works for a different success type, such as Result<Date>, with no new code. Frontend code uses this shape for form parsing, for data loading states and for anything where an error is an expected outcome rather than an exception.
Type parameters can have defaults, written type Box<T = string>, and a function can take several, as pluck does with T and K. Keep the list short: when a signature needs four type parameters the design is usually asking for something simpler.
Constraints and keyof
An unconstrained T could be anything, so the body can do almost nothing with it. A constraint with extends narrows what callers may pass and what the body may assume. In longest, T extends { length: number } accepts strings and arrays, since both have a numeric length, and still returns the exact type that came in.
keyof T is the union of the property names of T. An indexed access type T[K] is the type of the property named K. Together they type a function that reads a property by name. pluck takes an array of T and a key that must be one of its keys, and returns an array of whatever that property holds. pluck(products, 'paise') is number[], and pluck(products, 'title') is string[].
type Product = { id: number; title: string; paise: number } declare const products: Product[] declare function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] declare function longest<T extends { length: number }>(a: T, b: T): T pluck(products, 'price') longest(10, 20)
Two calls that break the constraints.
t3c.ts(6,17): error TS2345: Argument of type '"price"' is not assignable to parameter of type 'keyof Product'. t3c.ts(7,9): error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
Output (tsc 7.0.2, long lines wrapped)
Both mistakes are caught: 'price' is not a key of Product, and a number has no length. The error text says what the constraint required, which is the quickest way to read a generic error: find the constraint, then find which argument broke it.
A typed fetch is a cast
Frontend code often wraps fetch in a helper that takes the expected response type. It looks like this.
type User = { id: number; name: string } async function fetchJson<T>(url: string): Promise<T> { const res = await fetch(url) return (await res.json()) as T } const user = await fetchJson<User>('http://127.0.0.1:55810/user') console.log(typeof user.id, user.id + 1) console.log(user.name.toUpperCase())
The compiler accepts it, and every caller gets autocomplete for user.id. But the generic describes what you hope the server sent. res.json() returns untyped data, and as T tells the compiler to believe you. Nothing checks the response at runtime. A local server that sends the id as text shows the gap.
import { createServer } from 'node:http' const server = createServer((req, res) => { if (req.url === '/done') { res.end('bye'); server.close(); return } res.setHeader('content-type', 'application/json') res.end(JSON.stringify({ id: '7', name: 'Asha' })) }) server.listen(55810, '127.0.0.1')
The stub server for this run, on port 55810.
string 71
ASHAOutput (Node 24)
The type says number, the run printed string, and user.id + 1 produced 71, text glued to a number, with no error anywhere. The generic saved typing effort but gave no safety. The last lesson of this chapter shows how to check the data instead of trusting it.
What does K extends keyof T guarantee in pluck?
- The key argument must be the name of a property of
T, so a misspelt name is a compile error.
Why did fetchJson<User> print string for typeof user.id?
- The
as Tcast only changes what the compiler believes. The server sent the id as text and nothing validated it.
What does the constraint T extends { length: number } allow?
- Any type with a numeric
length, such as a string or an array, and the function returns the same type it received.
Part 4 · Utility and mapped types
Built-in utility types
Real code derives types from other types: a form draft where every field is optional, a card that shows two fields of a product, a record without its internal id. TypeScript ships utility types for the common cases, so you derive the shape instead of copying it and letting the copies drift apart.
| Utility | Result for Product |
|---|---|
Partial<Product> | every property optional |
Pick<Product, 'title' | 'paise'> | only those two properties |
Omit<Product, 'stock'> | everything except stock |
Readonly<Product> | every property read-only |
Record<number, Product> | an object keyed by number |
Each one is built from two features you can use yourself: mapped types and conditional types. First, two mistakes that the derived types catch.
type Product = { id: number title: string paise: number stock: number } type Card = Pick<Product, 'title' | 'paise'> const card: Card = { title: 'Notebook' } const frozen: Readonly<Product> = { id: 1, title: 'Notebook', paise: 12000, stock: 9, } frozen.stock = 8
t4b.ts(9,7): error TS2741: Property 'paise' is missing in type '{ title: string; }' but required in type 'Card'. t4b.ts(14,8): error TS2540: Cannot assign to 'stock' because it is a read-only property.
Output (tsc 7.0.2, long lines wrapped)
Pick made paise required in Card, so the draft without it fails. Readonly turned the assignment to stock into an error. Both come straight from the definition of Product, so changing Product changes them.
Mapped types
A mapped type builds a new object type by looping over the keys of another. The syntax { [K in keyof T]: ... } reads as: for every key K of T, make a property. The right-hand side can change the value type, add ? or readonly, or rename the key with as.
type Product = { id: number title: string paise: number stock: number } type Draft = Partial<Product> type Card = Pick<Product, 'title' | 'paise'> type NoStock = Omit<Product, 'stock'> type ById = Record<number, Product> type Nullable<T> = { [K in keyof T]: T[K] | null } type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] } type Strip<T> = T extends null | undefined ? never : T type Checks = [ Expect<Equal<Draft['id'], number | undefined>>, Expect<Equal<keyof Card, 'title' | 'paise'>>, Expect<Equal<keyof NoStock, 'id' | 'title' | 'paise'>>, Expect<Equal<ById[3], Product>>, Expect<Equal<Nullable<Card>['title'], string | null>>, Expect<Equal<keyof Getters<Card>, 'getTitle' | 'getPaise'>>, Expect<Equal<Strip<string | number | null>, string | number>>, ]
Mapped types, a conditional type and their checks.
Nullable keeps every key and widens each value to include null. Getters renames each key with a template literal type, so title becomes getTitle, and turns each value into a function. The Checks tuple at the bottom proves each result with the equality helper from the first lesson: if any claim were wrong the file would not compile.
no errors reported
Output (tsc 7.0.2, long lines wrapped)
That empty report is the proof. To see what a failing proof looks like, claim that a Partial card equals the original.
type Card = { title: string; paise: number } type Wrong = Expect<Equal<Partial<Card>, Card>>
Only the failing claim; the helper is the one from before.
t4d.ts(7,21): error TS2344: Type 'false' does not satisfy the constraint 'true'.
Output (tsc 7.0.2, long lines wrapped)
Conditional types
A conditional type chooses between two types with the syntax A extends B ? X : Y. It is an if statement for types. Its useful trick is that when A is a naked type parameter and you pass a union, the condition is applied to each member separately and the results are joined. This is called a distributive conditional type.
Strip<T> removes null and undefined. Given string | number | null, it tests string, then number, then null, keeps the first two and turns the last into never, which disappears from a union.
Watch for each member of string | number | null being tested on its own
Read it as steps
A distributive conditional type tests each member of a union on its own.
Wrapping the parameter in a tuple, as [T] extends [null], turns distribution off, so the whole union is tested at once. Both behaviours are checked below.
type Strip<T> = T extends null | undefined ? never : T type Wrapped<T> = [T] extends [null] ? never : T type Checks = [ Expect<Equal<Strip<string | number | null>, string | number>>, Expect<Equal<Wrapped<string | null>, string | null>>, Expect< Equal<Wrapped<string | number | null>, string | number | null> >, ]
Both forms, with their checks.
no errors reported
Output (tsc 7.0.2, long lines wrapped)
The checks pass. Strip distributes and drops null. Wrapped sees a union that is not entirely null and returns it unchanged. Distribution is what makes built-ins such as NonNullable and Exclude work, and it is a common source of surprise when a union you expected to be tested as a whole is not.
Part 5 · Typing the DOM and events
What the DOM types say
The browser's API is described by the dom library type definitions. The compiler includes them when lib contains "dom", and without them even document is unknown.
const box = document.querySelector('#box') console.log(box)
t5c.ts(1,13): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'. t5c.ts(2,1): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
Output (tsc 7.0.2, --lib es2023 only)
The DOM is full of things that may not exist, so its types are honest. querySelector returns Element | null, and getElementById returns HTMLElement | null. A plain Element has no value, and the query may find nothing. Both facts show up as errors.
const name = document.querySelector('#name') console.log(name.value) const field = document.querySelector<HTMLInputElement>('#name') field.addEventListener('input', (e) => { console.log(e.target.value) })
t5a.ts(2,13): error TS18047: 'name' is possibly 'null'. t5a.ts(2,18): error TS2339: Property 'value' does not exist on type 'Element'. t5a.ts(5,1): error TS18047: 'field' is possibly 'null'. t5a.ts(6,15): error TS18047: 'e.target' is possibly 'null'. t5a.ts(6,24): error TS2339: Property 'value' does not exist on type 'EventTarget'.
Output (tsc 7.0.2, long lines wrapped)
Passing a generic fixes the first problem: querySelector<HTMLInputElement>('#name') returns HTMLInputElement | null. It does not fix the second, so the field line still says the value is possibly null. The last error is about events, which the next page covers.
Tag names and the element map
The DOM types also know about tag names. The library declares an interface, HTMLElementTagNameMap, that maps each tag to its element type: input to HTMLInputElement, td to HTMLTableCellElement, and so on. createElement and the query methods use it, so a tag name written as a literal gives you the precise type with no generic and no assertion.
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false type Expect<T extends true> = T const made = document.createElement('input') const byTag = document.querySelector('input') const byClass = document.querySelector('.name') const many = document.querySelectorAll('td') type Checks = [ Expect<Equal<typeof made, HTMLInputElement>>, Expect<Equal<typeof byTag, HTMLInputElement | null>>, Expect<Equal<typeof byClass, Element | null>>, Expect<Equal<typeof many, NodeListOf<HTMLTableCellElement>>>, ]
Tag names give precise types; the Equal helper is the one from lesson 1.
no errors reported
Output (tsc 7.0.2, long lines wrapped)
The empty report means all four claims hold. createElement('input') is an HTMLInputElement. querySelector('input') is that type or null, because the query can still miss. A class selector such as .name is a plain Element | null, because the compiler does not parse CSS and cannot know what the selector matches. querySelectorAll('td') gives a NodeListOf of cells.
Two more facts save time. dataset values are strings or undefined, because attributes are text, and getAttribute returns string | null. Neither is a number even when the markup looks like one, so convert on purpose. For a custom element you register, add its tag to the map by merging an interface in a declare global block, the same declaration merging from the first lesson, and createElement will return your class.
Events and targets
Every event type names its payload. addEventListener('submit', ...) on a form gives a SubmitEvent, and 'input' gives an InputEvent. The compiler picks the type from the event name through a map of event names to types, so you rarely write it.
The surprise is event.target. It is typed EventTarget | null, because the event may have started on any descendant, not on the element that holds the listener. To read value you must narrow it. An instanceof HTMLInputElement check does that, and it is also a real check at runtime. event.currentTarget is different at runtime: it is the element the listener is attached to. Its declared type, though, is also EventTarget | null, because it is declared once on the Event interface, which knows nothing about your element. Inside a function listener, the compiler does type this as the element.
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false type Expect<T extends true> = T const form = document.createElement('form') const email = document.createElement('input') form.addEventListener('submit', (e) => { type C = [Expect<Equal<typeof e, SubmitEvent>>] }) email.addEventListener('input', function (e) { type C = [ Expect<Equal<typeof e, InputEvent>>, Expect<Equal<typeof e.target, EventTarget | null>>, Expect<Equal<typeof e.currentTarget, EventTarget | null>>, Expect<Equal<typeof this, HTMLInputElement>>, ] })
The event types the compiler infers, proved with the Equal helper.
no errors reported
Output (tsc 7.0.2, long lines wrapped)
All five claims hold. The event names pick SubmitEvent and InputEvent, both targets are EventTarget | null, and this is an HTMLInputElement. So reading currentTarget.value still needs a check or an assertion, which is why the next file uses one.
The as operator is a type assertion. It is a promise to the compiler, not a check. Use instanceof when the element could be something else, and an assertion only when you control the markup.
A typed form handler
This file combines the pieces: elements looked up with generics, a null guard that throws early, a typed submit handler, a narrowed delegated click handler using closest with a generic, and a deliberate mistake at the end.
const form = document.querySelector<HTMLFormElement>('#signup') const email = document.querySelector<HTMLInputElement>('#email') const out = document.querySelector('#out') if (!form || !email || !out) throw new Error('missing element') form.addEventListener('submit', (e: SubmitEvent) => { e.preventDefault() out.textContent = 'Saved ' + email.value.trim().toLowerCase() }) email.addEventListener('input', (e) => { const el = e.currentTarget as HTMLInputElement el.classList.toggle('long', el.value.length > 10) }) document.addEventListener('click', (e) => { if (!(e.target instanceof HTMLElement)) return const row = e.target.closest<HTMLTableRowElement>('tr') out.setAttribute('data-last-row', row?.dataset.id ?? 'none') }) const city = document.querySelector<HTMLInputElement>('#city')! try { console.log(city.value.trim()) } catch (err) { console.log((err as Error).message) }
no errors reported
Output (tsc 7.0.2, long lines wrapped)
It compiles cleanly. The compiled JavaScript was loaded into a page in Chrome 157 with a form, a table row and a div with the id city, then driven with a typed value, a submit and a click on a cell.
console: Cannot read properties of undefined (reading 'trim')
out: Saved asha@example.com
row: r7Output (Chrome 157)
The first line is the mistake: #city is a div, but the generic claimed it was an input. The compiler allowed city.value.trim() because the generic is an assertion, and the page failed with a TypeError because a div has no value. After that, the submit handler saved a lower-cased, trimmed address, and the delegated click found its row. The console: prefix comes from the test script. As with fetchJson, a type argument you supply is not verified.
Why is event.target typed EventTarget | null and not the element you attached the listener to?
- The event may originate on any descendant, so the compiler cannot know.
- At runtime
currentTargetis the element holding the listener, but its declared type is alsoEventTarget | null.
Part 6 · Checking data at runtime
Types are erased
TypeScript types exist only while you edit and compile. The emitted JavaScript contains no trace of them, and a running page cannot ask what type a value had. Data that crosses a boundary, such as a JSON response, a postMessage, a stored value or a URL parameter, is therefore untrusted whatever your annotations say.
The lessons on generics and the DOM each showed the result of ignoring that. JSON.parse returns any, which turns the checker off, so any property access compiles. Annotating the result as unknown is the safer start: it permits no operations until you narrow it.
const raw = JSON.parse('{"id":"A-9"}') const typed: unknown = JSON.parse('{"id":"A-9"}') console.log(raw.id.toUpperCase()) console.log(typed.id)
t6b.ts(5,13): error TS18046: 'typed' is of type 'unknown'.
Output (tsc 7.0.2, long lines wrapped)
Only the unknown use is flagged. The any use compiles, and would fail at run time if id were missing.
A hand-written parser
The fix is a function that takes unknown, checks each field with ordinary typeof and array tests, and returns the typed result or throws. After it, the rest of the program can trust the type because the data was verified at the door.
type Order = { id: string; paise: number; items: string[] } function parseOrder(data: unknown): Order { if (typeof data !== 'object' || data === null) { throw new TypeError('order must be an object') } const o = data as Record<string, unknown> if (typeof o.id !== 'string') throw new TypeError('id must be text') if (typeof o.paise !== 'number' || !Number.isInteger(o.paise)) { throw new TypeError('paise must be a whole number') } const items = o.items const isText = (i: unknown) => typeof i === 'string' if (!Array.isArray(items) || !items.every(isText)) { throw new TypeError('items must be a list of text') } return { id: o.id, paise: o.paise, items } }
Each check narrows o step by step, and the final return statement type-checks because every field has been proved. A loop feeds it a valid order, a wrong paise, a wrong item and null.
const inputs = [ '{"id":"A-9","paise":49900,"items":["bottle"]}', '{"id":"A-9","paise":"499.00","items":["bottle"]}', '{"id":"A-9","paise":49900,"items":[7]}', 'null', ] for (const text of inputs) { try { console.log(parseOrder(JSON.parse(text))) } catch (e) { console.log((e as Error).message) } }
The calling loop.
{ id: 'A-9', paise: 49900, items: [ 'bottle' ] }
paise must be a whole number
items must be a list of text
order must be an objectOutput (Node 24)
Each bad input is rejected with a message that names the field, so a bug in the server response is found where the data arrives rather than three screens later. Return the parsed value instead of the raw one, as the function does, so extra fields cannot slip through unchecked.
Reusable guards
Writing the whole parser each time is wasteful when only the check changes. A guard is a function with a type predicate, and a generic helper can accept any guard and return a typed value or null. This is a common shape for reading stored data, where the text may be missing, corrupted by an older version of the app, or edited by hand.
type Guard<T> = (x: unknown) => x is T function readJson<T>(text: string, guard: Guard<T>): T | null { try { const value: unknown = JSON.parse(text) return guard(value) ? value : null } catch { return null } } type Cart = { count: number } const isCart: Guard<Cart> = (x): x is Cart => typeof x === 'object' && x !== null && typeof (x as { count?: unknown }).count === 'number' console.log(readJson('{"count":3}', isCart)) console.log(readJson('{"count":"3"}', isCart)) console.log(readJson('{oops', isCart))
{ count: 3 }
null
nullOutput (Node 24)
The helper catches a syntax error from JSON.parse, the guard rejects a value of the wrong shape, and both become null, so the caller has one case to handle for bad data. The valid input passes through typed as Cart. Note that guard(value) ? value : null is what narrows the variable: the compiler trusts the predicate, so a guard that is wrong makes the types wrong. Keep guards small and test them with bad inputs, as the loop above does.
Schema libraries and compiler limits
Writing a checker per type grows tedious, and the checker can drift from the type. Schema libraries such as Zod and Valibot let you declare the shape once and derive both the runtime check and the static type from it. They are packages outside this course, and the idea is the same as the hand-written function: parse unknown input, get a typed value or an error.
Two compiler facts help here. First, TypeScript 7.0, released on 8 July 2026, is a native port of the compiler written in Go. It turns the options deprecated in 6.0, such as target: es5 and baseUrl, into errors, and strict is on by default. Run with no --strict flag, an untyped parameter is still an error, and an old target is refused.
t6f.ts(1,16): error TS7006: Parameter 'items' implicitly has an 'any' type.
Output (tsc 7.0.2, no --strict flag)
error TS5108: Option 'target=ES5' has been removed. Please remove it
from your configuration.Output (tsc 7.0.2, --target es5)
Release 7.0 also ships without a programmatic API. The team expects a new one in 7.1, so tools that call the compiler from JavaScript cannot use 7.0 yet. The command line is what this chapter uses. Note that strict does not include noUncheckedIndexedAccess. Without that flag, reading sizes[9] from a string[] is typed string, though the value is undefined.
const sizes = ['S', 'M', 'L'] const second = sizes[1] console.log(second.toLowerCase()) const ninth = sizes[9] console.log(ninth.toLowerCase())
no errors reported
Output (tsc 7.0.2, default strict)
t6c.ts(3,13): error TS18048: 'second' is possibly 'undefined'. t6c.ts(5,13): error TS18048: 'ninth' is possibly 'undefined'.
Output (tsc 7.0.2, with noUncheckedIndexedAccess)
With the flag, every indexed read includes undefined, and both uses are flagged. At runtime the second one throws, so the flag matches what the run does.
m t6c.ts:5 console.log(ninth.toLowerCase()) TypeError: Cannot read properties of undefined (reading 'toLowerCase')
Output (Node 24, stack frames omitted)
Second, Node 24 runs .ts files by stripping types, which works only for syntax that is pure annotation. Features that generate code, such as enum, are refused.
All chapters · Previous: Promises, Async Code and the Browser Event Loop