Check JavaScript-oriented programs with types before running their compiled output.
Before starting: JavaScript functions, arrays, objects, and modules.
Practice project: Validate an external score record and calculate a type-safe report.
Module 1: Introduction, Tooling & Compilation Pipeline
- TypeScript Overview, JavaScript SuperSet & Static Type System
- Environment Setup: Node.js, npm, tsc Compiler & ts-node Execution
- tsconfig.json Architecture: Compiler Options, Target, Module & Strict Modes
- First TypeScript Program: Transpilation Workflow, Source Maps & Watch Mode
- Type Annotations vs Type Inference: Best Practices & Contextual Typing
Module 2: Fundamental Types & Type System Core
- Primitive Types: number, string, boolean, null, undefined, bigint & symbol
- Special Types: any (Escape Hatch) vs unknown (Safe Top Type) vs never (Bottom Type)
- Typed Arrays & Fixed-Length Tuples: Readonly Arrays, Labels & Variadic Elements
- Enums: Numeric Enums, String Enums, Heterogeneous & Inlined const enums
- void, object, Object & {} Differences: Non-Primitive Typing
Module 3: Type Aliases, Unions & Narrowing
- Type Aliases: Defining Semantic Names for Primitives, Objects & Unions
- Union Types: Composing Flexible Types & Accessing Shared Properties
- Intersection Types: Combining Multiple Object Types & Capabilities
- Literal Types: String, Numeric, Boolean Literals & Literal Widening
- Type Narrowing: typeof, instanceof, Truthiness & Equality Guards
Module 4: Advanced Type Narrowing & Custom Guards
- Discriminated Unions: Tagged Variants & Compile-Time Exhaustive Checks
- Custom Type Guards: Type Predicates (param is Type) & Assertion Functions
- Type Assertions & Non-Null Assertion: as Type, Angle Brackets & the ! Operator
- const Assertions (as const): Readonly Tuples, Literal Inference & Compile-Time Checks
- The satisfies Operator: Validating Conformance Without Type Widening
Module 5: Functions, Signatures & Overloads
- Function Type Signatures: Expressions, Call Signatures & Construct Signatures
- Optional, Default & Rest Parameters: Variable Arguments & Tuple Spreads
- Function Overloads: Overload Signatures vs Implementation Signatures
- Typing this in Functions: Explicit this Parameters & Built-in Utilities
- void vs undefined Return Types: Callback Assignability & Contextual Typing
Module 6: Interfaces & Object Shapes
- Interfaces: Object Contracts, Structural Typing & Declaration Merging
- Optional & Readonly Properties: Mutability Control & Excess Property Checks
- Index Signatures: Dynamic Property Dictionaries & Record<K, V> Utility
- Interface Inheritance: Extending Single & Multiple Interfaces
- Interfaces vs Type Aliases: Architectural Comparison & Selection Matrix
Module 7: Classes, Object-Oriented TS & Modifiers
- Classes: Fields, Constructors, Parameter Properties & Definite Assignment
- Access Modifiers: public, private, protected & ECMAScript #private Fields
- readonly & static Class Members: Static Blocks & Class Constants
- Abstract Classes & Methods: Polymorphic Hierarchies vs Interfaces
- Class Implementation: The implements Keyword & Separation of Concerns
Module 8: Generics & Type Parameterization
- Generic Functions: Type Parameters <T>, Identity Functions & Multi-Generics
- Generic Interfaces & Classes: Parameterized Data Structures & Collections
- Generic Constraints: The extends Keyword & keyof Property Safety
- Default Type Arguments in Generics: Fallback Parameters & Ergonomics
- Practical Generic Utilities: Type-Safe Data Fetching, Mappers & Wrappers
Module 9: Advanced Type Manipulations & Mapped Types
- keyof & typeof Operators: Indexed Access Types & Type Queries
- Conditional Types: T extends U ? X : Y & Distributive Conditional Types
- Type Inference in Conditional Types: The infer Keyword & ReturnType
- Mapped Types: Homomorphic Transformations & Key Remapping with as
- Template Literal Types: String Pattern Matching & Intrinsic String Manipulation
Module 10: Utility Types, Decorators & Production Engineering
- Built-in Utility Types I: Partial, Required, Readonly, Record, Pick & Omit
- Built-in Utility Types II: Exclude, Extract, NonNullable, ReturnType & Awaited
- Modules & Namespaces: ES Modules, Type-Only Imports & Module Resolution
- Ambient Declarations & .d.ts Files: DefinitelyTyped (@types) & Global Augmentation
- Modern Decorators (Stage 3), Strict Configuration & Enterprise Best Practices
Trace changing state and check loop boundaries
A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.
Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.
PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
total ← total + value
RETURN totalCheck the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.
Test JavaScript without a test framework
Start by testing one small function outside the user interface. Node has a built-in test runner and assertion module. The input array below stays unchanged: reduce computes a total without assigning to its elements. A passing test checks observable behavior rather than how many loops the implementation uses.
Node.js 20+; save as an ES module (.mjs)
import test from "node:test";
import assert from "node:assert/strict";
function total(values) {
return values.reduce((sum, value) => sum + value, 0);
}
test("adds values without changing the input", () => {
const values = [4, 6];
assert.equal(total(values), 10);
assert.deepEqual(values, [4, 6]);
});
test("an empty total is zero", () => {
assert.equal(total([]), 0);
});Check the output
Two passing tests. The reporter format and timing depend on your Node version.Add a negative-number case. Decide whether strings are valid input and document your decision before changing the function.
Validate unknown data before using TypeScript types
TypeScript checks your program before execution; it does not turn a type assertion into an input check. Treat JSON, browser storage, and network responses as untrusted values. The guard below checks the fields used by the application. It deliberately rejects nonfinite numbers and missing names.
TypeScript compiler and Node.js; no third-party runtime libraries
type Score = { name: string; score: number };
function isScore(value: unknown): value is Score {
if (typeof value !== "object" || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record.name === "string"
&& typeof record.score === "number"
&& Number.isFinite(record.score);
}
const input: unknown = JSON.parse('{"name":"Asha","score":75}');
console.log(isScore(input) ? input.score + 5 : "Invalid score");Check the output
80Reject empty names and scores outside 0–100. Keep those business rules separate from the structural type check.
Catch and narrow unknown exceptions in TypeScript
In modern TypeScript, catch variables default to unknown rather than any. Because any JavaScript value can be thrown, always narrow the caught error with instanceof Error before accessing properties like message.
TypeScript compiler (tsc) and Node.js; no third-party libraries
function safeParse(jsonStr: string): string {
try {
const data: unknown = JSON.parse(jsonStr);
return typeof data === "object" && data !== null ? "Valid object" : "Primitive";
} catch (err: unknown) {
if (err instanceof Error) {
return "Caught error: invalid JSON";
}
return "Unknown exception caught";
}
}
console.log(safeParse('{"ready":true}'));
console.log(safeParse('{bad json}'));Check the output
Valid object
Caught error: invalid JSONCreate a custom error class AppError extending Error and narrow it specifically to handle application-level validation failures.
Open the TypeScript learning path on DevStudyHub · Play coding games on this blog
No comments:
Post a Comment
Please do not enter any spam link in the comment box.