DiscoveryVIP / TypeScript AcademyHelp

200 TypeScript and JavaScript glossary entries

TypeScript concepts appear first, followed by the JavaScript foundations they build on.

What TypeScript is

TypeScript adds a static type system to JavaScript.

TypeScript adds a static type system to JavaScript. A type describes a set of permitted values or operations; number accepts numeric values and rejects a text argument at this call. A compiler checks source before execution and emits JavaScript for the runtime. The annotations on price, quantity and the return value are erased from ordinary emitted code. They do not convert data or validate an incoming network response. Here the same function is visible as TypeScript, emitted JavaScript, actual diagnostics and actual output. Change one argument before experimenting with the function body.

function calculateTotal(price: number, quantity: number): number {
  return price * quantity;
}

console.log(calculateTotal(25, 3));
Open related lesson

JavaScript versus TypeScript

JavaScript determines runtime behavior, including coercion.

JavaScript determines runtime behavior, including coercion. TypeScript checks the declared contract without changing multiplication, addition or other runtime operators into safe alternatives. A typed parameter lets the compiler identify a caller that supplies text, but a value that bypasses checking can still fail at runtime. Compare the emitted file: type annotations disappear while the function and arithmetic remain. Use a compiler error and a separate logical-error test to see why both stages matter.

function addPrice(price: number, fee: number): number {
  return price + fee;
}
console.log(addPrice(25, 3));
Open related lesson

Static type checking

Static checking analyzes source rather than executing each possible input.

Static checking analyzes source rather than executing each possible input. An assignment to a number binding is checked when compiled; a later runtime action does not need to occur for that diagnostic to be produced. Checking is deliberately conservative and follows the available information. A correct type cannot prove a business rule such as a positive balance. Give each input an explicit runtime validation strategy when its data comes from outside the trusted program.

let stock: number = 8;
stock = 12;
console.log(stock);
Open related lesson

Running your first TypeScript program

Compile and Run performs two separate steps.

Compile and Run performs two separate steps. The compiler first reports errors and emits JavaScript only when its configured contract permits emission. The execution environment then runs that JavaScript and captures logs or exceptions. A successful compile is not a run, and a successful run covers only the inputs supplied. Keep source, emitted output and diagnostics visible together so a type annotation is not mistaken for a runtime check.

const price: number = 25;
const quantity: number = 4;
console.log(price * quantity);
Open related lesson

Understanding the compiler

A TypeScript program includes source files, compiler settings and declaration libraries.

A TypeScript program includes source files, compiler settings and declaration libraries. Parsing identifies syntax, checking analyzes types, and emission produces JavaScript. Standard declarations describe APIs such as console without implementing them. The academy bundles the actual compiler and libraries; it does not invent diagnostic messages. Its browser runner supports relative project modules and restricts network access, so a type declaration for an API does not guarantee that API exists in a worker.

const course: string = "Discovery";
console.log(course.toUpperCase());
Open related lesson

Strings

string describes text, including the empty string.

string describes text, including the empty string. Its methods return particular types: trim and toUpperCase return strings, while length is a number property. A string annotation is not a requirement that text be nonempty or an email address. Validate those domain rules separately. The type explorer uses the checker’s actual information at each source position, which can be more specific than a broad annotation in a narrowed context.

const learner: string = " Alex ";
console.log(learner.trim().toUpperCase());
Open related lesson

Numbers

TypeScript’s number uses JavaScript’s numeric behavior, including floating point, NaN and Infinity.

TypeScript’s number uses JavaScript’s numeric behavior, including floating point, NaN and Infinity. It does not distinguish currency, integers or positive counts by default. Use validation and domain models when those differences matter. toFixed returns display text rather than a new numeric storage format. A compiler-clean calculation can still use the wrong tax or discount operation; test expected results independently.

const price: number = 19.5;
const units: number = 2;
console.log((price * units).toFixed(2));
Open related lesson

Booleans

boolean accepts true and false rather than the strings "true" and "false".

boolean accepts true and false rather than the strings "true" and "false". A condition may narrow a value, but truthiness and equality have different meanings. Use explicit comparison for domain states that are not genuinely binary. The boolean type cannot prove that an approval was granted by an authorized person; it only describes the representation.

const approved: boolean = true;
console.log(approved ? "Ready" : "Review");
Open related lesson

Null and undefined

With strictNullChecks, null and undefined are separate from ordinary string and object values.

With strictNullChecks, null and undefined are separate from ordinary string and object values. A union such as string | null requires a check before calling string methods. Optional chaining safely handles a nullish access but can produce undefined, which a caller must still consider. Do not hide missing data with a non-null assertion unless a real invariant justifies it. The strict setting can be changed in the compiler lab to compare actual diagnostics.

function greeting(name: string | null): string {
  return name === null ? "Guest" : name.toUpperCase();
}
console.log(greeting(null));
console.log(greeting("Alex"));
Open related lesson

Type annotations

An annotation records a contract for a binding, parameter, property or return value.

An annotation records a contract for a binding, parameter, property or return value. It can clarify intent, but redundant annotations on obvious local values often add noise. Annotation syntax belongs to TypeScript and is usually erased during emission. A broad annotation can allow more values than a literal type, while an overly narrow one can reject legitimate usage. Prefer a clear boundary contract and let simple local expressions infer their types.

const title: string = "Layout workshop";
const seats: number = 12;
console.log(title + ": " + seats);
Open related lesson

Inferred variable types

TypeScript often infers a binding’s type from its initializer.

TypeScript often infers a binding’s type from its initializer. A let initialized with a number can be reassigned another number, but not text. The type explorer reads actual checker types rather than guessing from the spelling of the literal. Inference is not runtime validation and may intentionally widen a value to support later assignments. Inspect the declaration and a reference after control flow separately.

let total = 10;
total = 15;
console.log(total);
Open related lesson

Contextual typing

An expression can get its type from the place where it is used.

An expression can get its type from the place where it is used. A callback passed to a number array’s map method has a number parameter without an explicit annotation. If the surrounding context disappears, an unannotated parameter may become an implicit-any error under strict settings. Use actual checker information inside the callback to see where the type comes from.

const doubled = [2, 4, 6].map(value => value * 2);
console.log(doubled);
Open related lesson

Literal inference

A literal type denotes a particular value, such as "ready", rather than every possible string.

A literal type denotes a particular value, such as "ready", rather than every possible string. const bindings can retain literal information while mutable object properties may widen. An as const assertion requests readonly literal inference; it does not freeze the object at runtime. Literal unions are useful for finite application states that should reject misspelled values.

const state = "ready" as const;
function announce(value: "ready"): string { return value.toUpperCase(); }
console.log(announce(state));
Open related lesson

Type widening

Widening gives a mutable value a useful broader type.

Widening gives a mutable value a useful broader type. A let initialized with "draft" is generally string, while an explicitly annotated literal union restricts valid changes. Do not force every local value to be a literal if legitimate mutation needs a broader type. Use type information and a failing assignment to compare the contracts rather than treating const as a universal design rule.

let status: "draft" | "published" = "draft";
status = "published";
console.log(status);
Open related lesson

Explicit versus inferred types

Use explicit types at important boundaries and inference for clear local results.

Use explicit types at important boundaries and inference for clear local results. A function’s parameter type protects callers, while its local expression can be inferred. Explicit return annotations can prevent an accidental API change; inferred returns can be convenient for internal helpers. Neither choice removes the need for tests of calculations and invalid external input.

function subtotal(price: number, quantity: number) {
  const result = price * quantity;
  return result;
}
console.log(subtotal(12, 3));
Open related lesson

Typed arrays

number[] means an array whose elements are numbers.

number[] means an array whose elements are numbers. It does not encode its length, and reading an arbitrary index can produce undefined at runtime. noUncheckedIndexedAccess makes that uncertainty explicit for many indexed reads. Mutating methods such as push respect the element contract. Use a tuple when fixed positions have distinct meanings.

const scores: number[] = [8, 10];
scores.push(9);
console.log(scores.reduce((sum, score) => sum + score, 0));
Open related lesson

Alternative array syntax

Array<T> and T[] describe the same ordinary element relationship.

Array<T> and T[] describe the same ordinary element relationship. The generic form can make unions or nested types clearer in some contexts, while the bracket form is concise. Choose a consistent project style rather than assuming one is more type-safe. Nested arrays need a clear distinction between row and cell types.

const rows: Array<Array<number>> = [[1, 2], [3, 4]];
console.log(rows.flat().reduce((sum, value) => sum + value, 0));
Open related lesson

Readonly arrays

ReadonlyArray<T> and readonly T[] prevent mutation through that reference at compile time.

ReadonlyArray<T> and readonly T[] prevent mutation through that reference at compile time. They do not deeply freeze nested objects or guarantee that another mutable reference cannot change the same array. Functions that only read should accept readonly inputs, which also permits callers with ordinary arrays. To transform, create a new array instead of pushing into the readonly one.

function total(values: readonly number[]): number {
  return values.reduce((sum, value) => sum + value, 0);
}
console.log(total([2, 3, 5]));
Open related lesson

Tuples

A tuple models a known sequence of positions, potentially with different types.

A tuple models a known sequence of positions, potentially with different types. A [string, number] pair communicates a label followed by a quantity. The compiler checks required positions and their types, while runtime arrays remain ordinary JavaScript arrays. Destructuring gives the positions meaningful local names. Validate untrusted arrays before asserting a tuple type.

const entry: [string, number] = ["Notebook", 3];
const [name, quantity] = entry;
console.log(name + ": " + quantity);
Open related lesson

Typed collections

Typed arrays work with local transformations such as filter, map and reduce.

Typed arrays work with local transformations such as filter, map and reduce. The array element shape provides contextual types for each callback. Filtering by a Boolean business property is not the same as validating an unknown object. Keep source collections intact when deriving a report and test empty inputs as well as typical records.

type Order = { amount: number; approved: boolean };
const orders: Order[] = [{amount: 20, approved: true}, {amount: 10, approved: false}];
console.log(orders.filter(order => order.approved).reduce((sum, order) => sum + order.amount, 0));
Open related lesson

Function parameter types

Parameters define what callers may supply.

Parameters define what callers may supply. A numeric signature rejects a string before execution, but it does not prove the numeric input is finite, positive or within a domain range. Runtime guards should implement those additional requirements. Keep the error close to the public boundary and test both compile-time misuse and runtime-invalid numbers.

function area(width: number, height: number): number {
  return width * height;
}
console.log(area(4, 5));
Open related lesson

Function return types

A return annotation constrains values produced along the function’s paths.

A return annotation constrains values produced along the function’s paths. It helps detect an accidental string result from a calculation. A function that logs a value has not necessarily returned it. Control flow should account for all required paths, and tests should verify actual results independently from the type annotation.

function percentage(part: number, whole: number): number {
  return part / whole * 100;
}
console.log(percentage(3, 4));
Open related lesson

Optional parameters

A parameter marked ? may be omitted and is potentially undefined inside the function.

A parameter marked ? may be omitted and is potentially undefined inside the function. Handle that case rather than calling methods blindly. Optional does not mean null unless null is also in the contract. A default value or nullish-coalescing fallback can be appropriate depending on whether empty strings or zero should be preserved.

function greet(name?: string): string {
  return "Hello, " + (name ?? "Guest");
}
console.log(greet());
console.log(greet("Alex"));
Open related lesson

Default parameters

A default parameter supplies a value when an argument is omitted or undefined.

A default parameter supplies a value when an argument is omitted or undefined. It does not replace an explicit null automatically. The initializer can inform the parameter’s type. Keep default behavior predictable and test an explicit non-default argument so the function does not accidentally ignore its input.

function shipping(total: number, fee = 5): number {
  return total + fee;
}
console.log(shipping(20));
console.log(shipping(20, 0));
Open related lesson

Function type signatures

A function type describes parameter and return relationships independently of one implementation.

A function type describes parameter and return relationships independently of one implementation. It can model a callback, strategy or dependency. Parameter names document intent but compatibility depends on the type relationship. Strict function variance rules matter when callbacks accept different input sets. Start with a clear signature and inspect the actual assignment diagnostic.

type Operation = (a: number, b: number) => number;
const sum: Operation = (a, b) => a + b;
console.log(sum(4, 6));
Open related lesson

Object types

An object type describes required properties and their types rather than a nominal class identity.

An object type describes required properties and their types rather than a nominal class identity. An object with a compatible structure can satisfy the contract. Property annotations do not construct or validate a runtime object. Excess-property checks on fresh literals catch many mistakes but are not a general guarantee that an object has no extra fields.

const product: {name: string; price: number} = {name: "Notebook", price: 12};
console.log(product.name + ": " + product.price);
Open related lesson

Required properties

A required property must be present with a compatible value where the contract is checked.

A required property must be present with a compatible value where the contract is checked. Missing and undefined are not identical design choices. Making a field optional just to silence an error can weaken every consumer. Decide whether the domain actually permits absence, then enforce that decision at both the static and runtime boundaries.

type Contact = {name: string; email: string};
const contact: Contact = {name: "Alex", email: "alex@example.com"};
console.log(contact.email);
Open related lesson

Optional properties

A ? property may be absent, so reading it can produce undefined.

A ? property may be absent, so reading it can produce undefined. exactOptionalPropertyTypes distinguishes an absent property from assigning undefined unless the declared type explicitly includes it. Optional chaining and nullish coalescing can express safe access, but they should match real product behavior rather than hide an unexpectedly missing value.

type Profile = {name: string; nickname?: string};
function label(profile: Profile): string { return profile.nickname ?? profile.name; }
console.log(label({name: "Alex"}));
Open related lesson

Readonly properties

readonly prevents assignment through the typed reference; it does not freeze an object at runtime or recursively make every nested field immutable.

readonly prevents assignment through the typed reference; it does not freeze an object at runtime or recursively make every nested field immutable. Use it to communicate ownership and protect APIs against accidental mutation. A copied object can represent an update while preserving the original. Test shared-reference behavior before assuming readonly is a complete immutability system.

type Product = {readonly id: string; price: number};
const product: Product = {id: "P1", price: 12};
console.log(product.id);
Open related lesson

Nested object structures

Nested types model relationships such as an order’s customer and address.

Nested types model relationships such as an order’s customer and address. Each level needs a clear contract; optional levels require narrowing before access. Deeply nested types can reveal a useful domain model or unnecessary complexity. Keep data transformation separate from rendering and validate every untrusted nested object instead of asserting the outer type only.

type Order = {id: string; customer: {name: string; address: {city: string}}};
const order: Order = {id:"O1",customer:{name:"Alex",address:{city:"Toronto"}}};
console.log(order.customer.address.city);
Open related lesson

Creating interfaces

An interface names an object-shaped contract and can be reused across variables and functions.

An interface names an object-shaped contract and can be reused across variables and functions. It describes the required structure rather than generating a constructor. Interfaces can merge declarations, which is useful in some library scenarios and surprising if names collide. Keep module boundaries explicit and inspect the properties the checker actually sees.

interface Learner { name: string; completed: number; }
const learner: Learner = {name:"Alex",completed:3};
console.log(learner.name + ": " + learner.completed);
Open related lesson

Type aliases

A type alias gives a name to a type expression, including objects, unions, tuples and primitives.

A type alias gives a name to a type expression, including objects, unions, tuples and primitives. The alias itself is erased; it does not create a runtime wrapper or a new nominal identity. Choose names that express domain responsibility. An alias can improve documentation, but a simple alias of string does not prevent assigning any ordinary string.

type Status = "draft" | "ready";
const status: Status = "ready";
console.log(status);
Open related lesson

Extending interfaces

An interface can extend another compatible object contract and add properties.

An interface can extend another compatible object contract and add properties. This models a structural relationship, not automatic runtime inheritance. Required properties from the base remain required. Conflicting property types should be redesigned rather than papered over with an assertion. Use the generated property table to inspect the complete resulting structure.

interface Person { name:string; }
interface Employee extends Person { department:string; }
const employee:Employee={name:"Alex",department:"Design"};
console.log(employee.department);
Open related lesson

Combining object types

An intersection requires a value to satisfy both sides.

An intersection requires a value to satisfy both sides. It does not mean either side is enough. Compatible object properties combine, while incompatible same-name properties can create an impossible requirement. Inspect the resulting type and required properties before building data around it. At runtime the result is still a normal object.

type Named={name:string};
type Priced={price:number};
const item:Named & Priced={name:"Journal",price:18};
console.log(item.name + ": " + item.price);
Open related lesson

Interfaces versus aliases

Both interfaces and aliases can describe object contracts.

Both interfaces and aliases can describe object contracts. Aliases also name unions and other expressions; interfaces support extension and declaration merging. Neither is universally better. Prefer a consistent style that fits the API and avoid relying on accidental merging. This example intentionally merges an interface in one module so the final required structure is visible.

interface RecordItem { id:string; }
interface RecordItem { label:string; }
const item:RecordItem={id:"R1",label:"Reviewed"};
console.log(item.label);
Open related lesson

Union types

A union permits values from one of several alternatives.

A union permits values from one of several alternatives. Before narrowing, only operations valid for every alternative are safe. number | string does not mean the value is both simultaneously. Avoid broad unions that permit incoherent application states; discriminated unions often make the relationship clearer. Observe how the checker’s type changes inside each branch.

function label(value:string|number):string {
  return typeof value === "number" ? value.toFixed(1) : value.toUpperCase();
}
console.log(label(4));
console.log(label("ready"));
Open related lesson

Literal unions

A finite union of string literals models choices such as sort direction or request state.

A finite union of string literals models choices such as sort direction or request state. It catches misspellings while preserving normal string values at runtime. A union is not a runtime list, so a selector control still needs an actual array of options. Validate incoming text against the allowed set instead of asserting it belongs.

type Direction="ascending"|"descending";
function arrow(direction:Direction):string{return direction === "ascending" ? "Up" : "Down";}
console.log(arrow("ascending"));
Open related lesson

Intersection types

An intersection combines requirements, often to compose small capabilities.

An intersection combines requirements, often to compose small capabilities. It is not a set of common object keys and does not select the runtime overlap of two objects. A value must have all required fields with compatible types. Conflicting primitives can reduce to never; inspect the compiler’s actual result instead of relying on a misleading Venn diagram.

type HasId={id:string};
type HasState={state:"open"|"closed"};
const task:HasId & HasState={id:"T1",state:"open"};
console.log(task.state);
Open related lesson

Discriminated unions

A shared literal property can identify which union member is present.

A shared literal property can identify which union member is present. After checking that discriminant, TypeScript exposes the corresponding fields. This models relationships that optional properties on one broad object often fail to enforce. Keep the switch exhaustive and validate external data before trusting its discriminant.

type Result={kind:"success";value:number}|{kind:"error";message:string};
function display(result:Result):string {
  return result.kind === "success" ? String(result.value) : result.message;
}
console.log(display({kind:"success",value:7}));
Open related lesson

Modeling application states

A state model should make invalid combinations difficult to represent.

A state model should make invalid combinations difficult to represent. A loading state should not simultaneously require successful data or a failure message. Discriminated unions express those alternatives and help rendering logic stay aligned. They do not automatically schedule asynchronous work or prevent stale responses; those are runtime design concerns.

type State={status:"idle"}|{status:"loading"}|{status:"ready";items:string[]}|{status:"error";message:string};
function describe(state:State):string {
  if(state.status === "ready") return state.items.join(", ");
  if(state.status === "error") return state.message;
  return state.status;
}
console.log(describe({status:"ready",items:["HTML","CSS"]}));
Open related lesson

Narrowing with typeof

typeof checks a runtime primitive category and informs control-flow analysis.

typeof checks a runtime primitive category and informs control-flow analysis. Remember that typeof null is "object", so an object check alone is insufficient. A narrowed identifier can have different types at different source positions; the explorer records those actual checker types. Keep the validation condition connected to the value you later use.

function size(value:string|number):number {
  if(typeof value === "string") return value.length;
  return value;
}
console.log(size("Type"));
Open related lesson

Narrowing with instanceof

instanceof checks a runtime prototype relationship.

instanceof checks a runtime prototype relationship. It is useful for classes such as Date or custom classes that actually exist at runtime, but interfaces and aliases are erased and cannot be instanceof targets. Cross-realm objects can complicate this check. Prefer structural validation for plain JSON data rather than assuming it has a class prototype.

function year(value:Date|string):string {
  if(value instanceof Date) return String(value.getUTCFullYear());
  return value;
}
console.log(year(new Date("2026-01-01T00:00:00Z")));
Open related lesson

Narrowing with the in operator

The in operator checks property presence at runtime and can narrow a union of object shapes.

The in operator checks property presence at runtime and can narrow a union of object shapes. Presence does not necessarily prove a useful value, especially for optional properties. Validate the property’s type as well when data is unknown. Avoid using an inherited property as an authorization signal; this lesson focuses on known typed unions.

type Email={email:string};type Phone={phone:string};
function contact(value:Email|Phone):string {
  return "email" in value ? value.email : value.phone;
}
console.log(contact({email:"alex@example.com"}));
Open related lesson

User-defined type guards

A predicate return such as value is User tells the compiler how a successful check narrows data.

A predicate return such as value is User tells the compiler how a successful check narrows data. TypeScript trusts that predicate signature; it does not prove the implementation actually validates every field. Implement the check using real runtime evidence and test deceptive values. A poorly written guard can compile and still make unsafe claims.

type User={name:string};
function isUser(value:unknown):value is User {
  return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string";
}
const input:unknown={name:"Alex"};
console.log(isUser(input) ? input.name : "Invalid");
Open related lesson

Exhaustive checking

A value narrowed to never represents an impossible remaining case under the current static model.

A value narrowed to never represents an impossible remaining case under the current static model. Passing an unhandled union member to an assertNever helper makes a missing branch a compiler error. The helper still throws at runtime if untrusted data bypasses the static model. Keep discriminants explicit and rerun checks when adding a new state.

type Shape={kind:"square";side:number}|{kind:"circle";radius:number};
function assertNever(value:never):never{throw new Error("Unhandled shape");}
function area(shape:Shape):number {
  switch(shape.kind){case "square":return shape.side**2;case "circle":return Math.PI*shape.radius**2;default:return assertNever(shape);}
}
console.log(area({kind:"square",side:4}));
Open related lesson

Understanding any

any largely opts a value out of static checking and allows unsafe operations to spread.

any largely opts a value out of static checking and allows unsafe operations to spread. It can be useful at a migration boundary, but prefer unknown when a value needs validation. A compiler-clean any program can still call a missing method and throw. This lesson’s runtime counterexample demonstrates why suppressing diagnostics is not the same as making code safe.

let value:any="hello";
console.log(value.toUpperCase());
Open related lesson

Understanding unknown

unknown accepts any incoming value but requires narrowing before most operations.

unknown accepts any incoming value but requires narrowing before most operations. It makes uncertainty visible at boundaries such as parsed JSON or caught errors. Unlike any it prevents accidentally trusting a value’s shape. A successful check must cover the actual fields and types the program uses; an assertion merely suppresses the uncertainty.

function upper(value:unknown):string {
  if(typeof value !== "string") return "Invalid";
  return value.toUpperCase();
}
console.log(upper("safe"));
console.log(upper(12));
Open related lesson

Understanding never

never represents no possible value in a static position.

never represents no possible value in a static position. A function returning never does not normally complete: it always throws or never terminates. It is different from void, which describes no useful return value. Use never for exhaustive checks and impossible states rather than inventing an ordinary placeholder value. The runtime remains JavaScript and needs its own failure handling.

function fail(message:string):never { throw new Error(message); }
try { fail("Invalid input"); } catch(error) { console.log(error instanceof Error ? error.message : "Unknown"); }
Open related lesson

Understanding void

void describes a function result the caller is not expected to use.

void describes a function result the caller is not expected to use. A function with an explicit void return annotation cannot return a useful typed value, while contextual void callback assignability has subtleties: callers may ignore a returned value. Distinguish this static contract from runtime undefined. A log operation is an effect, not a returned calculation result.

function report(message:string):void { console.log(message); }
report("Saved for review");
Open related lesson

Type assertions and their limits

An assertion tells the compiler to treat a value as a type; it does not convert, validate or add missing properties.

An assertion tells the compiler to treat a value as a type; it does not convert, validate or add missing properties. Prefer a checked parser for external data. Assertions can be reasonable when information exists outside the checker, but document the invariant and test it. Comparing emitted JavaScript makes the absence of a runtime check visible.

const value:unknown="TypeScript";
const text=value as string;
console.log(text.length);
Open related lesson

Generic functions

A generic parameter expresses a relationship between inputs and outputs rather than choosing one fixed type.

A generic parameter expresses a relationship between inputs and outputs rather than choosing one fixed type. identity<T> returns the same T supplied or inferred by the caller. It is not any: operations inside the function must be valid for the permitted T. Inspect resolved call signatures to see actual inferred arguments and return types.

function first<T>(values:readonly T[]):T|undefined { return values[0]; }
console.log(first(["Alex","Jordan"]));
console.log(first([4,7]));
Open related lesson

Generic interfaces

A generic interface describes a reusable shape whose member types depend on a parameter.

A generic interface describes a reusable shape whose member types depend on a parameter. Box<string> and Box<number> share structure but accept different values. Use the parameter consistently so the interface expresses a real relationship. A generic interface does not validate JSON automatically; runtime construction or parsing must still establish the shape.

interface Box<T>{value:T;}
const box:Box<number>={value:7};
console.log(box.value*2);
Open related lesson

Generic classes

A generic class connects the types of stored values and methods on an instance.

A generic class connects the types of stored values and methods on an instance. Each instance fixes its type argument through annotation or construction. Static members do not share the instance’s type parameter in the same way. Keep runtime storage separate from type relationships and test empty collections when methods can return undefined.

class Store<T>{constructor(private value:T){} get():T{return this.value;}}
const store=new Store<string>("Ready");
console.log(store.get());
Open related lesson

Generic constraints

A constraint limits the operations valid on a generic input while preserving its more specific type.

A constraint limits the operations valid on a generic input while preserving its more specific type. T extends {length:number} allows reading length but does not mean the input must be a string. A constraint is a static requirement, not a runtime validator. Design the smallest capability the function needs rather than an unnecessarily broad class hierarchy.

function size<T extends {length:number}>(value:T):number{return value.length;}
console.log(size("Types"));
console.log(size([1,2]));
Open related lesson

Reusable typed data structures

A useful collection API preserves relationships between keys, records and return types.

A useful collection API preserves relationships between keys, records and return types. A Map<string,T> can represent an indexed repository, but a missing key still yields undefined. Generics do not guarantee uniqueness or persistence; implement those runtime invariants. Prefer simple operations and test absent records and updates independently.

class Repository<T extends {id:string}>{private records=new Map<string,T>();add(value:T):void{this.records.set(value.id,value);}get(id:string):T|undefined{return this.records.get(id);}}
const repo=new Repository<{id:string;title:string}>();repo.add({id:"R1",title:"Review"});
console.log(repo.get("R1")?.title);
Open related lesson

TypeScript classes

A class exists at runtime and can also describe instance types.

A class exists at runtime and can also describe instance types. Fields and methods implement behavior; annotations document and check their contracts. Definite initialization is checked under strict settings. A class is not required for every data shape: a plain interface plus functions is often enough. Compare the emitted class with erased annotations to see which parts survive.

class Counter { value=0; increment():void { this.value+=1; } }
const counter=new Counter();counter.increment();
console.log(counter.value);
Open related lesson

Constructors

A constructor initializes a runtime instance.

A constructor initializes a runtime instance. Parameter properties are a TypeScript shorthand that also emits field initialization, so they are not merely erased annotations. Decide which invariants construction must enforce and reject invalid runtime values there when appropriate. Constructor parameter types protect checked callers, not arbitrary JavaScript or decoded data.

class Product { constructor(public name:string, public price:number){} }
const product=new Product("Notebook",12);
console.log(product.name + ": " + product.price);
Open related lesson

Access modifiers

public, protected and private control TypeScript access rules.

public, protected and private control TypeScript access rules. TypeScript private is not identical to JavaScript #private runtime fields; inspect the emitted code before assuming data secrecy. protected permits access through the class hierarchy, while public is available to callers. Expose useful behavior rather than mutable internal storage whenever that supports the design.

class Account { private balance=10; deposit(amount:number):void{this.balance+=amount;} getBalance():number{return this.balance;} }
const account=new Account();account.deposit(5);
console.log(account.getBalance());
Open related lesson

Inheritance

extends establishes a runtime prototype relationship and a static instance relationship.

extends establishes a runtime prototype relationship and a static instance relationship. A subclass can override behavior, but the inherited contract must remain compatible. Prefer composition when the relationship is collaboration rather than a genuine substitutable specialization. Call super appropriately when initializing derived instances and test behavior through the base contract.

class Message { constructor(public text:string){} render():string{return this.text;} }
class LoudMessage extends Message { override render():string{return this.text.toUpperCase();} }
console.log(new LoudMessage("ready").render());
Open related lesson

Implementing interfaces

implements checks that a class’s instance side satisfies an interface; it does not inject method implementations or change runtime behavior.

implements checks that a class’s instance side satisfies an interface; it does not inject method implementations or change runtime behavior. It also does not automatically annotate every method parameter, so write the necessary signatures. A public interface can keep consumers independent from internal storage choices. Test the actual class behavior in addition to structural compatibility.

interface Printable { print():string; }
class Report implements Printable { print():string{return "Report ready";} }
console.log(new Report().print());
Open related lesson

The keyof operator

keyof produces the permitted property-key union of a type.

keyof produces the permitted property-key union of a type. It is a type-level operation and does not enumerate a runtime object. Combine it with a generic key parameter to preserve the relationship between an object and the selected property’s type. An unchecked string is not automatically a safe key. Validate dynamic external keys before indexing.

function get<T,K extends keyof T>(object:T,key:K):T[K]{return object[key];}
const person={name:"Alex",age:30};
console.log(get(person,"name"));
Open related lesson

typeof in type positions

typeof can query a value’s static type in a type expression.

typeof can query a value’s static type in a type expression. It is different from the runtime operator that returns strings such as "number". This is useful for deriving configuration types without copying a shape. Literal widening still affects the result, and as const can preserve a deliberately narrow configuration.

const config={theme:"light",pageSize:20};
type Config=typeof config;
const next:Config={theme:"dark",pageSize:10};
console.log(next.pageSize);
Open related lesson

Indexed access types

T[K] selects a property type at compile time.

T[K] selects a property type at compile time. It can derive a nested value contract or an array element type without duplicating it. An indexed access type is not the same as reading a runtime property and cannot prove that an external key exists. Keep key constraints and optionality visible when designing reusable helpers.

type User={id:string;score:number};
type Score=User["score"];
const score:Score=12;
console.log(score);
Open related lesson

Mapped types

A mapped type transforms properties by iterating a key union in the type system.

A mapped type transforms properties by iterating a key union in the type system. It can add readonly or optional modifiers or change value relationships. No runtime loop or object is generated. A separate implementation must build corresponding values when needed. Inspect actual property types and optional flags rather than assuming the transformation worked from its name.

type Flags<T>={[K in keyof T]:boolean};
type Settings={email:string;theme:string};
const flags:Flags<Settings>={email:true,theme:false};
console.log(flags.email);
Open related lesson

Conditional types

A conditional type selects a branch based on assignability.

A conditional type selects a branch based on assignability. With a naked generic type parameter it can distribute over unions, which is useful but sometimes surprising. infer can extract a related type within a branch. This logic runs in the checker, not at runtime; a type-level classifier does not inspect an incoming JSON value.

type Label<T>=T extends string?"text":"other";
const label:Label<string>="text";
console.log(label);
Open related lesson

Partial and Required

Partial makes every property optional, while Required removes optional modifiers.

Partial makes every property optional, while Required removes optional modifiers. These utility types transform static relationships and do not fill default values or validate updates. A patch operation should apply only allowed fields and decide what absence means. exactOptionalPropertyTypes can matter when undefined is used explicitly rather than a key being omitted.

type User={name:string;age:number};
const patch:Partial<User>={age:31};
const user:User={name:"Alex",age:30};
console.log({...user,...patch});
Open related lesson

Pick and Omit

Pick selects keys from a type and Omit removes keys from its static view.

Pick selects keys from a type and Omit removes keys from its static view. Neither removes properties from an existing runtime object. If sensitive fields must not leave a boundary, construct a new public object deliberately rather than merely annotating a private one as Omit. Tests should inspect actual serialized output.

type User={id:string;name:string;secret:string};
const publicUser:Pick<User,"id"|"name">={id:"U1",name:"Alex"};
console.log(publicUser);
Open related lesson

Record

Record<K,V> creates an object type with keys K and values V.

Record<K,V> creates an object type with keys K and values V. A finite literal-key union can require every listed entry. Record<string,V> is an index-signature-like model and does not guarantee a particular runtime string is present. noUncheckedIndexedAccess helps expose many missing-key reads. Use a Map when its runtime API fits better.

type Status="open"|"closed";
const counts:Record<Status,number>={open:3,closed:2};
console.log(counts.open+counts.closed);
Open related lesson

Readonly

Readonly<T> prevents writing top-level properties through that reference.

Readonly<T> prevents writing top-level properties through that reference. It is shallow; nested objects can still be mutable unless their types also restrict mutation. It also does not emit Object.freeze. Use explicit ownership and update patterns rather than assuming a utility type creates runtime immutability.

type Settings={theme:string;size:number};
const settings:Readonly<Settings>={theme:"light",size:18};
console.log(settings.theme);
Open related lesson

ReturnType and Parameters

Utility types can derive related contracts from a function instead of copying them.

Utility types can derive related contracts from a function instead of copying them. ReturnType extracts the static return type, Parameters produces a tuple of parameter types, and Awaited unwraps awaited values. Overloads and generics have documented subtleties, so inspect actual checker results. These utilities do not call the function or produce runtime argument validation.

function total(price:number,quantity:number):number{return price*quantity;}
type Args=Parameters<typeof total>;
const args:Args=[12,3];
const result:ReturnType<typeof total>=total(...args);
console.log(result);
Open related lesson

Imports and exports

Modules create explicit dependencies and scope declarations.

Modules create explicit dependencies and scope declarations. Relative imports name project files, while package imports need a resolver and installed implementation. A type-only import can be erased, while a runtime import needs emitted code at execution. The academy checks and bundles relative CommonJS output for its sandbox; exported browser applications include a separate ES-module build.

import {double} from "./math";
console.log(double(6));
Open related lesson

Organizing source files

Group code by responsibility: domain models, pure rules, adapters and UI.

Group code by responsibility: domain models, pure rules, adapters and UI. Module boundaries prevent accidental global merging and make dependencies visible. More files are not automatically better; avoid circular dependencies and unrelated shared utility piles. The file picker edits real source, and diagnostics identify which file contains each problem.

import {formatMoney} from "./format";
import type {Product} from "./models";
const item:Product={name:"Notebook",price:12};
console.log(formatMoney(item.price));
Open related lesson

Module resolution

The compiler resolves a module specifier according to configured rules.

The compiler resolves a module specifier according to configured rules. Finding a declaration is distinct from finding a runtime implementation. Browser, bundler and Node projects can require different choices. This static lab deliberately supports relative virtual files and rejects external packages in the runtime. An unresolved path should produce the actual compiler diagnostic, not a fabricated error panel.

import {name} from "./settings";
console.log(name);
Open related lesson

Declaration files

A .d.ts file describes types without supplying runtime implementation.

A .d.ts file describes types without supplying runtime implementation. It can model an existing JavaScript library, but inventing a declaration cannot make a missing global exist. Keep declaration and implementation synchronized and verify actual runtime behavior. This example pairs a local declaration with an emitted JavaScript implementation so both stages can be observed.

import {triple} from "./legacy";
console.log(triple(4));
Open related lesson

Understanding tsconfig.json

A tsconfig describes project files and compiler options.

A tsconfig describes project files and compiler options. strict is a group of checks rather than a runtime mode. Browser output targets, module format and resolution must fit the deployment environment. The academy exposes a documented subset of options and pins its compiler version. Compare actual diagnostics under strictNullChecks or noUncheckedIndexedAccess rather than assuming a setting silently fixes source.

const values:number[]=[4,7];
const first=values[0];
console.log(first);
Open related lesson

Typed DOM selection

DOM selection can return null and often a general Element.

DOM selection can return null and often a general Element. Use a suitable generic where appropriate and a real null check before accessing control-specific fields. An assertion that a selector found an input does not verify the DOM. The Browser preview runs actual emitted code; worker execution has no document. Keep the markup and typed selectors aligned.

const button=document.createElement("button");
button.textContent="Preview ready";
document.body.append(button);
console.log(button.textContent);
Open related lesson

Typed browser events

Event types describe available fields, but event.target may not be the element you assume.

Event types describe available fields, but event.target may not be the element you assume. currentTarget and a known selected control can provide a safer relationship. Narrow target with instanceof when needed and handle null. A typed event listener must still implement actual behavior and be tested using keyboard as well as pointer input.

const button=document.createElement("button");button.textContent="Count";
let count=0;
button.addEventListener("click",()=>{count+=1;button.textContent=String(count);});
document.body.append(button);button.click();
console.log(button.textContent);
Open related lesson

Typed form handling

A form handler should validate actual values before turning them into a domain model.

A form handler should validate actual values before turning them into a domain model. FormData entries can be strings or files, and missing entries are possible. Preventing the default submission only keeps the example local; it does not save to a server. Keep visible labels, error messages and an appropriate submit path in the real interface.

const form=document.createElement("form");
const input=document.createElement("input");input.name="name";input.value="Alex";form.append(input);
const value=new FormData(form).get("name");
console.log(typeof value === "string" ? value.trim() : "Invalid");
Open related lesson

Typed application state

State should represent valid combinations and be updated through clear operations.

State should represent valid combinations and be updated through clear operations. A discriminated union can distinguish idle, ready and error states, while a reducer can make transitions explicit. The type system checks the model but does not prevent stale asynchronous responses or persist state automatically. Derive the UI from actual state rather than mutating unrelated labels independently.

type State={count:number};type Action={type:"increment"}|{type:"reset"};
function reduce(state:State,action:Action):State{return {count:action.type === "increment"?state.count+1:0};}
console.log(reduce({count:2},{type:"increment"}).count);
Open related lesson

Building typed user interfaces

A typed UI connects a validated model to real DOM updates and events.

A typed UI connects a validated model to real DOM updates and events. Type-safe data does not guarantee accessible markup, sensible focus or clear status messages. Use textContent for untrusted text, native controls for actions and tests that observe actual interaction. This small render function creates real list items rather than printing a JSON-only simulation of an interface.

type Task={title:string;done:boolean};
const tasks:Task[]=[{title:"Read source",done:false},{title:"Test output",done:true}];
const list=document.createElement("ul");
tasks.forEach(task=>{const item=document.createElement("li");item.textContent=task.title;list.append(item);});
document.body.append(list);
console.log(list.children.length);
Open related lesson

Typed promises

Promise<T> describes a future result, not an already available T.

Promise<T> describes a future result, not an already available T. Use await or a callback to access the resolved value, and account for rejection. A promise’s type does not describe all possible error values. The local examples use deterministic fixtures and actual asynchronous JavaScript; no remote request is implied.

async function loadCount():Promise<number>{return 7;}
loadCount().then(value=>console.log(value*2));
Open related lesson

Async and await

An async function returns a promise even when its body returns a plain value.

An async function returns a promise even when its body returns a plain value. await pauses that function until a value settles; it does not make all operations run in a global sequential order. Catch failures at an intentional boundary and avoid leaving rejected promises unobserved. Test ordering and invalid inputs in the runtime, not only the return annotation.

async function report():Promise<void>{
  const value:number=await Promise.resolve(5);
  console.log(value+1);
}
report().catch(error=>console.log(String(error)));
Open related lesson

Typing API responses

An interface for an API response documents the expected shape but does not verify the received JSON.

An interface for an API response documents the expected shape but does not verify the received JSON. Treat the decoded value as unknown at the boundary and validate it before using a typed model. The request lab uses clearly labeled local fixtures so the same failures can be reproduced without a key or network access. Keep transport, parsing and schema failures separate.

type Weather={city:string;temperature:number};
const fixture:Weather={city:"Toronto",temperature:18};
console.log(fixture.city + ": " + fixture.temperature);
Open related lesson

Runtime data validation

The compiler checks source-level relationships, while a runtime validator inspects actual values.

The compiler checks source-level relationships, while a runtime validator inspects actual values. JSON.parse returns a value that should be treated as unknown rather than trusted through an assertion. Check object/null/array distinctions and every field the consumer will use. Reject unknown categories or invalid numeric values according to the application contract, and test malicious or malformed fixtures.

type Feedback={category:"support"|"praise";summary:string};
function isFeedback(value:unknown):value is Feedback{return typeof value === "object" && value !== null && "category" in value && (value.category === "support" || value.category === "praise") && "summary" in value && typeof value.summary === "string";}
const input:unknown=JSON.parse('{"category":"support","summary":"Invoice request"}');
console.log(isFeedback(input)?input.summary:"Invalid");
Open related lesson

Asynchronous failures

catch values are unknown under strict settings because JavaScript can throw any value.

catch values are unknown under strict settings because JavaScript can throw any value. Narrow an Error before reading its message and define an honest fallback for other values. A typed successful response does not eliminate rejected promises or malformed content. Bound retries and distinguish user cancellation from provider failure in larger applications.

async function load():Promise<number>{throw new Error("Fixture unavailable");}
async function main():Promise<void>{try{console.log(await load());}catch(error){console.log(error instanceof Error?error.message:"Unknown failure");}}
main().catch(error=>console.log(String(error)));
Open related lesson

Understanding compiler diagnostics

A diagnostic has a code, category, source location and message from the actual compiler.

A diagnostic has a code, category, source location and message from the actual compiler. Start with the first meaningful cause rather than fixing every downstream message independently. The highlighted source range and checker type table help compare the actual and expected contracts. The academy never replaces compiler feedback with an authored imitation; explanatory text is labeled separately.

function double(value:number):number{return value*2;}
console.log(double(8));
Open related lesson

Strict compiler settings

Strict options expose uncertainty earlier but do not make JavaScript runtime values trustworthy.

Strict options expose uncertainty earlier but do not make JavaScript runtime values trustworthy. noImplicitAny catches missing parameter information; strictNullChecks makes nullish states explicit; noUncheckedIndexedAccess adds uncertainty to many index reads. exactOptionalPropertyTypes refines absence versus explicit undefined. Inspect actual diagnostics as settings change and avoid silencing them with any merely to obtain a green panel.

function upper(value:string|undefined):string{return value?.toUpperCase()??"Missing";}
console.log(upper(undefined));
Open related lesson

Investigating type errors

A type error may reveal a caller mistake, an inaccurate contract or a missing runtime check.

A type error may reveal a caller mistake, an inaccurate contract or a missing runtime check. Determine which one before changing types. Broadening to any can hide the evidence while preserving the bug. Use the smallest failing input and compare actual compiler information at the declaration and use site. Then run independent tests to catch logical errors the compiler cannot infer.

type Product={name:string;price:number};
function total(product:Product,quantity:number):number{return product.price*quantity;}
console.log(total({name:"Notebook",price:12},2));
Open related lesson

Testing TypeScript applications

Type checking and behavioral testing answer different questions.

Type checking and behavioral testing answer different questions. A number-returning function can still add a discount rather than subtract it. An assertion should compare actual output with an independently chosen expected result. Test typical, boundary and invalid cases, and ensure the test itself fails for a known mutation. Do not derive every expected result from the same implementation under test.

function discount(price:number,rate:number):number{return price*(1-rate);}
const result=discount(100,.2);
if(result !== 80)throw new Error("Discount regression");
console.log("Discount verified");
Open related lesson

Refactoring JavaScript to TypeScript

Migration can begin with useful boundary types and runtime checks instead of annotating every variable.

Migration can begin with useful boundary types and runtime checks instead of annotating every variable. checkJs and JSDoc support incremental work where appropriate. Preserve behavior with tests before refactoring, then reduce implicit any and unsafe assertions deliberately. A type annotation must reflect the actual data contract, not merely the first sample encountered.

function sum(values:readonly number[]):number{return values.reduce((a,b)=>a+b,0);}
console.log(sum([2,3,5]));
Open related lesson

Reusable typed components

A reusable component exposes a clear typed contract while keeping rendering and behavior understandable.

A reusable component exposes a clear typed contract while keeping rendering and behavior understandable. Generic props can connect item data to display callbacks, but accessibility and lifecycle remain runtime responsibilities. Prefer a small explicit API to a giant union of unrelated options. Test the actual DOM interaction when implementing a browser component.

type Renderer<T>=(item:T)=>string;
function renderList<T>(items:readonly T[],render:Renderer<T>):string{return items.map(render).join(" | ");}
console.log(renderList([{name:"Alex"}],item=>item.name));
Open related lesson

Typed application architecture

Separate domain data, pure rules, adapters and rendering.

Separate domain data, pure rules, adapters and rendering. Interfaces describe dependencies so tests can substitute deterministic implementations without pretending they are live services. Types should express real relationships across boundaries, while runtime validators handle untrusted inputs. The module dependency graph is derived from actual import declarations and can reveal unnecessary coupling.

interface Repository{load():string[];}
function summary(repository:Repository):string{return repository.load().join(", ");}
const fixture:Repository={load:()=>["Read","Test"]};
console.log(summary(fixture));
Open related lesson

Error-handling strategies

An explicit result union can make expected failures part of the API rather than throwing for every invalid value.

An explicit result union can make expected failures part of the API rather than throwing for every invalid value. Exceptions remain useful for other boundaries, but callers need a consistent contract. A result type does not guarantee that the error message is useful or that a failure has no side effects. Test both branches and keep operational errors distinct from invalid input.

type Result<T>={ok:true;value:T}|{ok:false;message:string};
function divide(a:number,b:number):Result<number>{return b===0?{ok:false,message:"Zero divisor"}:{ok:true,value:a/b};}
const result=divide(8,0);
console.log(result.ok?result.value:result.message);
Open related lesson

Reviewing AI-generated TypeScript

Verify generated source with the actual compiler, runtime tests and reference documentation.

Verify generated source with the actual compiler, runtime tests and reference documentation. AI can invent APIs, use an assertion instead of validation or weaken a model with any. Ask for a minimal change and discriminating tests, then inspect emitted code and actual behavior. A model’s claim that code compiled or ran is not evidence. Core learning never needs a model to finish the exercise.

function parseCount(value:unknown):number|null{return typeof value === "number" && Number.isFinite(value) && value>=0?value:null;}
console.log(parseCount("3"));
console.log(parseCount(3));
Open related lesson

Maintaining larger applications

Keep public contracts small, dependencies explicit and strict checks consistent.

Keep public contracts small, dependencies explicit and strict checks consistent. Test behavior before changing a model and update all affected consumers intentionally. Utility types can reduce duplication but should not hide domain meaning. The lab’s multi-file resolver is intentionally a relative-project subset, not an npm toolchain. Exported projects include a pinned compiler and reproducible build instructions.

type Item={id:string;title:string};
function rename(item:Item,title:string):Item{return {...item,title};}
const original:Item={id:"I1",title:"Draft"};
console.log(rename(original,"Reviewed").title);
console.log(original.title);
Open related lesson

Planning a typed application

Start with the user’s task, trusted and untrusted inputs, valid states and measurable behavior.

Start with the user’s task, trusted and untrusted inputs, valid states and measurable behavior. A type model should clarify requirements rather than precede all understanding of the problem. Separate compile-time contracts from runtime validation, storage and UI. Write a success case and a failure case before implementation and state which integrations are fixtures.

type Requirement={task:string;verified:boolean};
const plan:Requirement[]=[{task:"Validate input",verified:true},{task:"Test failure",verified:false}];
console.log(plan.filter(item=>!item.verified).map(item=>item.task));
Open related lesson

Designing application data models

Choose stable identifiers, explicit optionality and finite states where the domain requires them.

Choose stable identifiers, explicit optionality and finite states where the domain requires them. Avoid combining unrelated values into one broad object with every property optional. A useful model supports operations and makes invalid combinations visible to the compiler. External input still needs runtime parsing into the model. Demonstrate one rejected shape as well as a valid record.

type Task={id:string;title:string;state:"open"|"done"};
const task:Task={id:"T1",title:"Review source",state:"open"};
console.log(task.state);
Open related lesson

Building typed application features

Implement one feature through validated input, a pure operation, state update and observable output.

Implement one feature through validated input, a pure operation, state update and observable output. Types connect those stages but do not create the user interface or persist data automatically. Keep a small working vertical slice before adding more features. Use actual state and DOM tests rather than static status labels that only look functional.

type Task={id:string;done:boolean};
function toggle(tasks:readonly Task[],id:string):Task[]{return tasks.map(task=>task.id===id?{...task,done:!task.done}:task);}
console.log(toggle([{id:"T1",done:false}],"T1"));
Open related lesson

Testing and compiling the application

A release needs a reproducible compiler version, clean diagnostics, behavioral tests, invalid-data cases and deployment instructions.

A release needs a reproducible compiler version, clean diagnostics, behavioral tests, invalid-data cases and deployment instructions. Strict checking is one gate, not proof of complete security, accessibility or logic. Test the exported project outside the academy and record which environments actually ran it. Keep known limitations and recovery steps alongside the source.

function total(values:readonly number[]):number{return values.reduce((sum,value)=>sum+value,0);}
if(total([2,3])!==5||total([])!==0)throw new Error("Regression");
console.log("Release checks passed");
Open related lesson

Independent TypeScript capstone

Present a complete typed feature with its inputs, model, validator, operation, interface and evidence.

Present a complete typed feature with its inputs, model, validator, operation, interface and evidence. Demonstrate both a successful task and a deliberate failure. Explain actual compiler diagnostics and why types do not replace runtime validation. Export all files, run the documented build and test the standalone application. Independent understanding is shown by explaining and extending the work, not by clicking through every lesson.

type Item={name:string;price:number;quantity:number};
function valid(item:Item):boolean{return Number.isFinite(item.price)&&item.price>=0&&Number.isInteger(item.quantity)&&item.quantity>0;}
function total(items:readonly Item[]):number{if(!items.every(valid))throw new Error("Invalid item");return items.reduce((sum,item)=>sum+item.price*item.quantity,0);}
console.log(total([{name:"Notebook",price:12,quantity:2}]));
Open related lesson

Programming

Writing instructions that a computer can execute.

Writing instructions that a computer can execute. The example shows its use in JavaScript source.

console.log("Hello");
Open related lesson

Program

A collection of instructions intended to accomplish a task.

A collection of instructions intended to accomplish a task. The example shows its use in JavaScript source.

console.log(2 + 3);
Open related lesson

Source code

The human-readable text of a program.

The human-readable text of a program. The example shows its use in JavaScript source.

let score = 1;
Open related lesson

Instruction

An operation described by source code.

An operation described by source code. The example shows its use in JavaScript source.

console.log("Run");
Open related lesson

Statement

A complete syntactic unit such as a declaration or expression statement.

A complete syntactic unit such as a declaration or expression statement. The example shows its use in JavaScript source.

let total = 5;
Open related lesson

Expression

Source that evaluates to a value.

Source that evaluates to a value. The example shows its use in JavaScript source.

5 * 3
Open related lesson

Value

A piece of data that a program can use.

A piece of data that a program can use. The example shows its use in JavaScript source.

42
Open related lesson

Syntax

The grammatical rules for valid source code.

The grammatical rules for valid source code. The example shows its use in JavaScript source.

console.log("Hello");
Open related lesson

Comment

Source text ignored during execution and intended for readers.

Source text ignored during execution and intended for readers. The example shows its use in JavaScript source.

// Explain the rule.
Open related lesson

Identifier

A name used to refer to a binding or other program entity.

A name used to refer to a binding or other program entity. The example shows its use in JavaScript source.

itemsInCart
Open related lesson

Keyword

A word reserved for a language construct.

A word reserved for a language construct. The example shows its use in JavaScript source.

const
Open related lesson

Semicolon

A statement separator or terminator in source syntax.

A statement separator or terminator in source syntax. The example shows its use in JavaScript source.

let x = 1;
Open related lesson

Parentheses

Symbols used for grouping or call argument lists.

Symbols used for grouping or call argument lists. The example shows its use in JavaScript source.

(5 + 2) * 3
Open related lesson

Brace

A symbol used to delimit blocks or object literals.

A symbol used to delimit blocks or object literals. The example shows its use in JavaScript source.

if (true) { console.log("yes"); }
Open related lesson

Bracket

A symbol used in array literals or property access.

A symbol used in array literals or property access. The example shows its use in JavaScript source.

items[0]
Open related lesson

Literal

Source syntax directly representing a value.

Source syntax directly representing a value. The example shows its use in JavaScript source.

"Hello"
Open related lesson

Console

A diagnostic interface where programs record messages.

A diagnostic interface where programs record messages. The example shows its use in JavaScript source.

console.log("Ready");
Open related lesson

Output

An observable result produced by execution.

An observable result produced by execution. The example shows its use in JavaScript source.

console.log(15);
Open related lesson

Input

Data supplied to a program or function.

Data supplied to a program or function. The example shows its use in JavaScript source.

greet("Alex")
Open related lesson

Algorithm

A defined sequence of steps for solving a problem.

A defined sequence of steps for solving a problem. The example shows its use in JavaScript source.

Read numbers, add them, display the sum.
Open related lesson

Variable

A named binding used to access a value.

A named binding used to access a value. The example shows its use in JavaScript source.

let score = 3;
Open related lesson

Binding

The association between a name and a value.

The association between a name and a value. The example shows its use in JavaScript source.

const title = "Course";
Open related lesson

Declaration

Syntax that introduces a binding.

Syntax that introduces a binding. The example shows its use in JavaScript source.

let count;
Open related lesson

Assignment

An operation that stores a value in an existing binding.

An operation that stores a value in an existing binding. The example shows its use in JavaScript source.

count = 2;
Open related lesson

Reassignment

Replacing the value associated with a binding.

Replacing the value associated with a binding. The example shows its use in JavaScript source.

count = 3;
Open related lesson

let

A block-scoped declaration that allows reassignment.

A block-scoped declaration that allows reassignment. The example shows its use in JavaScript source.

let count = 0;
Open related lesson

const

A block-scoped declaration that prevents reassignment of its binding.

A block-scoped declaration that prevents reassignment of its binding. The example shows its use in JavaScript source.

const rate = 0.1;
Open related lesson

var

An older function-scoped declaration with hoisting behavior.

An older function-scoped declaration with hoisting behavior. The example shows its use in JavaScript source.

var legacy = 1;
Open related lesson

Data type

A category describing what a value is and which operations apply.

A category describing what a value is and which operations apply. The example shows its use in JavaScript source.

typeof 5
Open related lesson

String

A primitive sequence of UTF-16 code units representing text.

A primitive sequence of UTF-16 code units representing text. The example shows its use in JavaScript source.

"JavaScript"
Open related lesson

Number

The standard numeric type using floating-point representation.

The standard numeric type using floating-point representation. The example shows its use in JavaScript source.

3.5
Open related lesson

Boolean

A primitive logical value, either true or false.

A primitive logical value, either true or false. The example shows its use in JavaScript source.

true
Open related lesson

null

An explicit primitive value often representing intentional absence.

An explicit primitive value often representing intentional absence. The example shows its use in JavaScript source.

const selected = null;
Open related lesson

undefined

A primitive often observed when a value was not supplied or returned.

A primitive often observed when a value was not supplied or returned. The example shows its use in JavaScript source.

let pending;
Open related lesson

NaN

A numeric value representing an invalid numeric result.

A numeric value representing an invalid numeric result. The example shows its use in JavaScript source.

Number("not a number")
Open related lesson

Infinity

A numeric value beyond finite magnitude.

A numeric value beyond finite magnitude. The example shows its use in JavaScript source.

1 / 0
Open related lesson

BigInt

An integer numeric type for arbitrarily large whole values.

An integer numeric type for arbitrarily large whole values. The example shows its use in JavaScript source.

123n
Open related lesson

Symbol

A primitive value with unique identity, often used as a property key.

A primitive value with unique identity, often used as a property key. The example shows its use in JavaScript source.

Symbol("id")
Open related lesson

Primitive

A non-object value such as a string, number or Boolean.

A non-object value such as a string, number or Boolean. The example shows its use in JavaScript source.

typeof "text"
Open related lesson

Type conversion

Creating a representation of a value in another type.

Creating a representation of a value in another type. The example shows its use in JavaScript source.

Number("12")
Open related lesson

Coercion

Conversion performed implicitly by a language operation.

Conversion performed implicitly by a language operation. The example shows its use in JavaScript source.

"5" + 2
Open related lesson

Truthy

A value that becomes true in Boolean context.

A value that becomes true in Boolean context. The example shows its use in JavaScript source.

Boolean("hello")
Open related lesson

Falsy

A value that becomes false in Boolean context.

A value that becomes false in Boolean context. The example shows its use in JavaScript source.

Boolean("")
Open related lesson

Immutability

The property of a value that cannot be changed in place.

The property of a value that cannot be changed in place. The example shows its use in JavaScript source.

"text".toUpperCase()
Open related lesson

Mutation

Changing the contents of an existing object or array.

Changing the contents of an existing object or array. The example shows its use in JavaScript source.

items.push("new");
Open related lesson

State

The current values relevant to an application.

The current values relevant to an application. The example shows its use in JavaScript source.

let count = 0;
Open related lesson

Reference

An identity-bearing relationship to an object value.

An identity-bearing relationship to an object value. The example shows its use in JavaScript source.

const other = original;
Open related lesson

Shallow copy

A new outer object that still shares nested referenced values.

A new outer object that still shares nested referenced values. The example shows its use in JavaScript source.

const copy = {...original};
Open related lesson

Deep copy

A copy that recreates supported nested data rather than sharing it.

A copy that recreates supported nested data rather than sharing it. The example shows its use in JavaScript source.

structuredClone(record)
Open related lesson

Serialization

Converting a supported value into a transport representation.

Converting a supported value into a transport representation. The example shows its use in JavaScript source.

JSON.stringify(record)
Open related lesson

Condition

An expression used to select a control-flow branch.

An expression used to select a control-flow branch. The example shows its use in JavaScript source.

score >= 5
Open related lesson

Branch

One possible path chosen by control flow.

One possible path chosen by control flow. The example shows its use in JavaScript source.

if (ready) { run(); }
Open related lesson

Loop

A construct that repeats operations while its rule allows it.

A construct that repeats operations while its rule allows it. The example shows its use in JavaScript source.

for (let i = 0; i < 3; i++) {}
Open related lesson

Iteration

One pass through a loop body.

One pass through a loop body. The example shows its use in JavaScript source.

console.log(i);
Open related lesson

Accumulator

A value carrying a running result across iterations.

A value carrying a running result across iterations. The example shows its use in JavaScript source.

sum += value;
Open related lesson

Counter

A binding that tracks a changing count or position.

A binding that tracks a changing count or position. The example shows its use in JavaScript source.

i++
Open related lesson

Infinite loop

Repetition whose stopping condition is never reached.

Repetition whose stopping condition is never reached. The example shows its use in JavaScript source.

while (true) {}
Open related lesson

Function

A callable unit of reusable behavior.

A callable unit of reusable behavior. The example shows its use in JavaScript source.

function double(n) { return n * 2; }
Open related lesson

Parameter

A binding declared to receive a function argument.

A binding declared to receive a function argument. The example shows its use in JavaScript source.

function greet(name) {}
Open related lesson

Argument

A value supplied in a call.

A value supplied in a call. The example shows its use in JavaScript source.

greet("Alex")
Open related lesson

Return value

The result given by a function to its caller.

The result given by a function to its caller. The example shows its use in JavaScript source.

return total;
Open related lesson

Callback

A function supplied to another operation for later or repeated invocation.

A function supplied to another operation for later or repeated invocation. The example shows its use in JavaScript source.

items.map(double)
Open related lesson

Arrow function

A function expression using arrow syntax and lexical this.

A function expression using arrow syntax and lexical this. The example shows its use in JavaScript source.

n => n * 2
Open related lesson

Scope

The region in which a binding can be accessed.

The region in which a binding can be accessed. The example shows its use in JavaScript source.

{ let local = 1; }
Open related lesson

Block scope

Visibility limited to the enclosing block.

Visibility limited to the enclosing block. The example shows its use in JavaScript source.

if (true) { let x = 1; }
Open related lesson

Global scope

The outer scope for a script environment.

The outer scope for a script environment. The example shows its use in JavaScript source.

globalThis
Open related lesson

Local scope

A scope belonging to an inner function or block.

A scope belonging to an inner function or block. The example shows its use in JavaScript source.

function f() { const local = 1; }
Open related lesson

Closure

A function retaining access to bindings from its creation environment.

A function retaining access to bindings from its creation environment. The example shows its use in JavaScript source.

function make(n) { return () => n; }
Open related lesson

Call stack

The active sequence of function calls waiting to finish.

The active sequence of function calls waiting to finish. The example shows its use in JavaScript source.

outer() calls inner()
Open related lesson

Stack frame

The execution context of a particular active function call.

The execution context of a particular active function call. The example shows its use in JavaScript source.

double(4)
Open related lesson

Recursion

A function invoking itself with a defined stopping case.

A function invoking itself with a defined stopping case. The example shows its use in JavaScript source.

factorial(n - 1)
Open related lesson

Base case

A condition that stops a recursive calculation.

A condition that stops a recursive calculation. The example shows its use in JavaScript source.

if (n === 0) return 1;
Open related lesson

Pure function

A function whose result depends on arguments and does not mutate external state.

A function whose result depends on arguments and does not mutate external state. The example shows its use in JavaScript source.

n => n * 2
Open related lesson

Side effect

An observable change outside a function’s returned value.

An observable change outside a function’s returned value. The example shows its use in JavaScript source.

element.textContent = "Updated";
Open related lesson

Hoisting

The observable early establishment of certain declarations in a scope.

The observable early establishment of certain declarations in a scope. The example shows its use in JavaScript source.

function declarations can be called before their source position
Open related lesson

Temporal dead zone

The region before a lexical binding is initialized where access throws.

The region before a lexical binding is initialized where access throws. The example shows its use in JavaScript source.

console.log(x); let x = 1;
Open related lesson

Destructuring

Syntax extracting values from arrays or object properties.

Syntax extracting values from arrays or object properties. The example shows its use in JavaScript source.

const {name} = person;
Open related lesson

Spread syntax

Syntax expanding iterable elements or copying object properties.

Syntax expanding iterable elements or copying object properties. The example shows its use in JavaScript source.

[...items]
Open related lesson

Rest parameter

A parameter collecting remaining arguments into an array.

A parameter collecting remaining arguments into an array. The example shows its use in JavaScript source.

function sum(...values) {}
Open related lesson

Default parameter

An initializer used when an argument is undefined.

An initializer used when an argument is undefined. The example shows its use in JavaScript source.

function greet(name = "friend") {}
Open related lesson

Array

An ordered, indexed object commonly used as a collection.

An ordered, indexed object commonly used as a collection. The example shows its use in JavaScript source.

["Learn", "Build"]
Open related lesson

Index

A numeric position used to access an array element.

A numeric position used to access an array element. The example shows its use in JavaScript source.

items[0]
Open related lesson

Element

A value stored at an array position.

A value stored at an array position. The example shows its use in JavaScript source.

items[1]
Open related lesson

Length

The array boundary or string code-unit count reported by length.

The array boundary or string code-unit count reported by length. The example shows its use in JavaScript source.

items.length
Open related lesson

Object

A value that groups named properties and has identity.

A value that groups named properties and has identity. The example shows its use in JavaScript source.

{name: "Alex"}
Open related lesson

Property

A key-value association on an object.

A key-value association on an object. The example shows its use in JavaScript source.

person.name
Open related lesson

Key

A string or symbol identifying an object property.

A string or symbol identifying an object property. The example shows its use in JavaScript source.

"name"
Open related lesson

Method

A callable property associated with an object.

A callable property associated with an object. The example shows its use in JavaScript source.

text.trim()
Open related lesson

Prototype

An object consulted during inherited property lookup.

An object consulted during inherited property lookup. The example shows its use in JavaScript source.

Object.getPrototypeOf(record)
Open related lesson

Class

Syntax for defining construction and prototype-based behavior.

Syntax for defining construction and prototype-based behavior. The example shows its use in JavaScript source.

class Counter {}
Open related lesson

Instance

An object created with a particular constructor.

An object created with a particular constructor. The example shows its use in JavaScript source.

new Counter()
Open related lesson

Constructor

A function used to initialize an object through new.

A function used to initialize an object through new. The example shows its use in JavaScript source.

constructor(name) { this.name = name; }
Open related lesson

this

A binding whose value depends on the call form, except lexical arrows.

A binding whose value depends on the call form, except lexical arrows. The example shows its use in JavaScript source.

this.name
Open related lesson

Getter

An accessor invoked when a property is read.

An accessor invoked when a property is read. The example shows its use in JavaScript source.

get total() { return this.price * this.qty; }
Open related lesson

Setter

An accessor invoked when a property is assigned.

An accessor invoked when a property is assigned. The example shows its use in JavaScript source.

set value(n) { this._value = n; }
Open related lesson

Static method

A method available on the class constructor rather than instances.

A method available on the class constructor rather than instances. The example shows its use in JavaScript source.

Math.abs(-2)
Open related lesson

Map collection

A keyed collection supporting arbitrary value keys.

A keyed collection supporting arbitrary value keys. The example shows its use in JavaScript source.

new Map()
Open related lesson

Set collection

A collection of unique values.

A collection of unique values. The example shows its use in JavaScript source.

new Set([1,1,2])
Open related lesson

Iterable

A value providing an iterator used by constructs such as for...of.

A value providing an iterator used by constructs such as for...of. The example shows its use in JavaScript source.

for (const item of items) {}
Open related lesson

Iterator

An object producing successive values with next().

An object producing successive values with next(). The example shows its use in JavaScript source.

items.values()
Open related lesson