JavaScript and TypeScript course · Module 6: TypeScript Basics
What is TypeScript and its advantages
In this lesson6
Introduction: The problem with the dinosaur park
Welcome to a new chapter of our Jurassic Park adventure! Imagine the following situation: the park's programmers created an access control system for the dinosaur enclosures, designed to protect both guests and employees. Everything worked great until one moment...
// access-control-system.js
function grantAccess(employee, accessLevel) {
if (employee.permissions >= accessLevel) {
return true;
}
return false;
}
// Elsewhere in the system
const drMalcolm = {
firstName: "Ian",
lastName: "Malcolm",
role: "Mathematician"
// oops... missing the 'permissions' field!
};
// Attempt to access the dinosaur enclosure
const accessToT_Rex = grantAccess(drMalcolm, 5);
console.log("Access to T-Rex enclosure:", accessToT_Rex); // false, but no error!
// Later in the code...
if (accessToT_Rex) {
open_gate_to_enclosure('t-rex'); // This operation will never execute
} else {
console.log("Dr. Malcolm has no access"); // This will run, but nobody noticed the bug
}Did you notice what went wrong? The drMalcolm object was missing the permissions property, causing the system to incorrectly deny him access! In JavaScript this situation generated no error - the permissions property was simply undefined, which when compared to a number gave a result of false.
Now imagine the consequences of this situation in a real dinosaur park:
- Dr. Malcolm cannot enter his work zone
- Security systems don't work as they should
- Worse - nobody knows there's a problem!
This is exactly where TypeScript comes in handy.
What is TypeScript?
TypeScript is a superset of JavaScript that adds optional static typing. It was created by Microsoft and is developed as an open source project.
Think of TypeScript as an advanced security system for Jurassic Park:
- JavaScript is a park without cameras and sensors - everything works until something goes wrong
- TypeScript is a park equipped with cameras, motion sensors and an alarm system that detects problems BEFORE the dinosaurs escape from their enclosures
The same situation in TypeScript would look like this:
// access-control-system.ts
// We define an interface specifying what an employee object should look like
interface Employee {
firstName: string;
lastName: string;
role: string;
permissions: number; // Required field!
}
function grantAccess(employee: Employee, accessLevel: number): boolean {
if (employee.permissions >= accessLevel) {
return true;
}
return false;
}
// Elsewhere in the system
const drMalcolm = {
firstName: "Ian",
lastName: "Malcolm",
role: "Mathematician"
// TypeScript will catch the error: Property 'permissions' is missing in type
// '{ firstName: string; lastName: string; role: string; }' but required in type 'Employee'.
};
// This line will cause a compilation error - TypeScript will protect us!
const accessToT_Rex = grantAccess(drMalcolm, 5);In the above example TypeScript will detect the error at the code-writing stage, before the software runs. It's like a warning system alerting us that the enclosure gate is open, before the dinosaur has a chance to escape!
The most important advantages of TypeScript
1. Early error detection
Like the monitoring system in Jurassic Park, TypeScript detects potential problems even at the code-writing stage:
function feedDinosaur(dinosaur: { species: string; dietType: string; }): void {
let food;
if (dinosaur.dietType === 'herbivore') {
food = 'fern leaves';
} else if (dinosaur.dietType === 'carnivore') {
food = 'meat';
}
console.log(`Feeding ${dinosaur.species} with food: ${food}`);
}
// TypeScript will warn that the typo 'herbivro' matches no condition
const triceratops = { species: 'Triceratops', dietType: 'herbivro' };
feedDinosaur(triceratops);
// Without TypeScript this dinosaur would receive "undefined" as food!2. Better code documentation
TypeScript acts like a detailed inventory of all dinosaurs in the park:
// Without TypeScript - what are these parameters? What does this function return?
function createEnclosure(id, name, capacity, fenceType) {
//
}
// With TypeScript - instant documentation!
function createEnclosure(
id: number,
name: string,
capacity: number,
fenceType: 'standard' | 'electric' | 'reinforced'
): { id: number; status: 'active' | 'under construction' | 'closed' } {
//
return { id, status: 'under construction' };
}3. Better IDE support (code completion)
Thanks to TypeScript, your development environment (IDE) will know exactly what operations you can perform on a given object:
const dinosaur = { name: 'Rex', species: 'T-Rex', weight: 8000 }
dinosaur.name.toUpperCase() // after the dot the editor suggests name, species and weight, after the second dot the string methods
dinosaur.height // error: Property 'height' does not exist on type '{ name: string; species: string; weight: number; }'It's like a map of Jurassic Park with detailed directions showing where the individual enclosures are and what dinosaurs are kept in them.
4. Safer refactoring
When you make changes to the park management system, TypeScript warns you about all places that need updating:
// Before refactoring
interface Dinosaur {
id: number;
species: string;
dangerous: boolean;
}
// After refactoring - changing the field type
interface Dinosaur {
id: number;
species: string;
threatLevel: number; // 1 to 10 instead of boolean
}
// TypeScript will point to all places where we used "dangerous"
// and now we need to use "threatLevel"5. Types for external libraries
Even if you use external libraries written in plain JavaScript, you can use type definition files that provide code completion and type checking:
// Installing types for the DNA analysis library
// npm install --save-dev @types/dino-dna-analyzer
import { analyzeDNA } from 'dino-dna-analyzer';
// Now TypeScript knows the types of parameters and return values
const result = analyzeDNA({
sequence: 'ACGTACGT',
baseSpecies: 'frog'
});
console.log(result.completeness); // TypeScript knows the available fields6. Support for modern JavaScript features
TypeScript lets you use the latest JavaScript features even if the target environment doesn't support them:
// Using modern JavaScript syntax
const dinosaurs = ['T-Rex', 'Velociraptor', 'Triceratops'];
const [mostDangerous, ...rest] = dinosaurs;
// Optional chaining and nullish coalescing
const data = {
park: {
// sector may not exist
}
};
const sectorName = data.park?.sector?.name ?? "Unknown sector";7. Gradual migration
One of the biggest advantages of TypeScript is the ability to gradually introduce it to existing JavaScript projects:
- Change the file extension from
.jsto.ts - Initially ignore errors using
// @ts-ignoreor theanytype - Gradually add types to the code, starting with the most critical parts
It's like gradually upgrading the security systems in Jurassic Park, sector by sector, instead of shutting down the entire park for renovations.
Limitations of TypeScript
Of course, like every technology, TypeScript has its limitations:
- Additional compilation step - TypeScript code must be converted to JavaScript before running
- Steep learning curve - for beginning JavaScript programmers, learning types can be a challenge
- False sense of security - TypeScript detects type-related errors, but doesn't protect against logic errors
- The
anytype - you can "cheat" the type system by usingany, which negates TypeScript's advantages
When is TypeScript worth using?
TypeScript works best in the following scenarios:
- Large projects with many programmers - like managing all of Jurassic Park
- Long-term projects - when code will be maintained for a long time
- Complex business applications - when errors can have serious consequences
- Libraries and Open Source tools - to make it easier for other programmers to use your code
Summary
TypeScript is like an advanced security system for Jurassic Park:
- JavaScript: "We have dinosaurs in cages, everything should be fine."
- TypeScript: "Every dinosaur is monitored, we have an alert at the slightest anomaly, and employees have clear instructions."
By adding typing to JavaScript code, you gain:
- Earlier error detection
- Better documentation
- More efficient programming tools
- Safer refactoring
In the next lessons we'll start exploring the TypeScript type system in detail and see how we can use it to build more reliable systems - ones that wouldn't let dinosaurs escape from the park!
Code for this lesson: index.ts
// TypeScript in Jurassic Park - Introduction and basics
console.log("Welcome to TypeScript in Jurassic Park!");
console.log("Let's learn about TypeScript and its benefits for safe code\n");
// ===========================================
// 1. Problem with JavaScript - no types
// ===========================================
console.log("=== 1. THE PROBLEM WITH JAVASCRIPT ===");
// JavaScript - problems with types
function grantAccessJS(employee: any, accessLevel: any): boolean {
// JavaScript has no type checking
if (employee.permissions >= accessLevel) {
return true;
}
return false;
}
// Unsafe data - no checking
const drMalcolmJS: any = {
name: "Ian Malcolm",
role: "Mathematician"
// The 'permissions' field is missing!
};
// This executes without error but returns an incorrect result
const accessJS = grantAccessJS(drMalcolmJS, 5);
console.log("JavaScript access result:", accessJS); // undefined >= 5 = false
console.log("JavaScript allows type errors at runtime");
console.log("Hard debugging");
console.log("No IntelliSense/autocomplete\n");
// ===========================================
// 2. TypeScript - solving the problem
// ===========================================
console.log("=== 2. TYPESCRIPT - THE SOLUTION ===");
// Interface definition for an employee
interface Employee {
name: string;
role: string;
permissions: number;
department?: string; // Optional field
}
// A function with TypeScript types
function grantAccess(employee: Employee, accessLevel: number): boolean {
if (employee.permissions >= accessLevel) {
return true;
}
return false;
}
// Correct data with types
const drMalcolm: Employee = {
name: "Ian Malcolm",
role: "Mathematician",
permissions: 3
};
const accessTS = grantAccess(drMalcolm, 5);
console.log("TypeScript access result:", accessTS);
console.log("TypeScript checks types at compile time");
console.log("Better IntelliSense and autocomplete");
console.log("Early error detection\n");
// ===========================================
// 3. Basic TypeScript types
// ===========================================
console.log("=== 3. BASIC TYPESCRIPT TYPES ===");
// Primitive types
let dinosaurName: string = "Tyrannosaurus Rex";
let dinosaurAge: number = 68000000;
let isExtinct: boolean = true;
let unknownData: unknown = "mysterious data";
let nothingHere: null = null;
let notDefined: undefined = undefined;
// Arrays
let dinosaurSpecies: string[] = ["T-Rex", "Triceratops", "Velociraptor"];
let dangerLevels: Array<number> = [9, 6, 8]; // Alternative syntax
// Tuple - array with fixed length and types
let dinosaurInfo: [string, number, boolean] = ["T-Rex", 8000, true];
// Enum - numbered constants
enum SecurityLevel {
Green = 1,
Yellow = 2,
Orange = 3,
Red = 4,
Critical = 5
}
let currentSecurity: SecurityLevel = SecurityLevel.Orange;
console.log("Current security level:", SecurityLevel[currentSecurity]);
// Union types - one of several types
type DinosaurDiet = "carnivore" | "herbivore" | "omnivore";
let trexDiet: DinosaurDiet = "carnivore";
// Literal types
type DinosaurPeriod = "Triassic" | "Jurassic" | "Cretaceous";
let period: DinosaurPeriod = "Cretaceous";
console.log("Basic TypeScript types defined!\n");
// ===========================================
// 4. Interfaces and object types
// ===========================================
console.log("=== 4. INTERFACES AND OBJECT TYPES ===");
// Interface for a dinosaur
interface Dinosaur {
readonly id: string; // Read-only
name: string;
species: string;
diet: DinosaurDiet;
weight: number;
dangerLevel: number;
isActive?: boolean; // Optional
// Methods in the interface
roar(): string;
feed(food: string): void;
}
// Implementing the interface
class TyrannosaurusRex implements Dinosaur {
readonly id: string;
name: string;
species: string;
diet: DinosaurDiet;
weight: number;
dangerLevel: number;
isActive: boolean;
constructor(name: string) {
this.id = `DINO-${Date.now()}`;
this.name = name;
this.species = "Tyrannosaurus Rex";
this.diet = "carnivore";
this.weight = 8000;
this.dangerLevel = 9;
this.isActive = true;
}
roar(): string {
return `${this.name} roars: ROAAAAAR!`;
}
feed(food: string): void {
console.log(`${this.name} eats ${food}`);
}
hunt(prey: string): string {
return `${this.name} hunts ${prey}`;
}
}
const rexy = new TyrannosaurusRex("Rexy");
console.log("Dinosaur created:", rexy.name);
console.log("Roar:", rexy.roar());
rexy.feed("goat");
// Extending interfaces
interface CarnivorousDinosaur extends Dinosaur {
huntingStyle: string;
packSize: number;
hunt(prey: string): string;
}
// Type aliases for complex types
type DinosaurCollection = {
[key: string]: Dinosaur;
};
type EnclosureStatus = "secure" | "breached" | "maintenance";
console.log("Interfaces and object types defined!\n");
// ===========================================
// 5. Generics - parametric types
// ===========================================
console.log("=== 5. GENERICS - PARAMETRIC TYPES ===");
// Generic function
function createContainer<T>(item: T): { content: T; timestamp: Date } {
return {
content: item,
timestamp: new Date()
};
}
// Usage with different types
const dinoContainer = createContainer<Dinosaur>(rexy);
const stringContainer = createContainer<string>("Important data");
const numberContainer = createContainer<number>(42);
console.log("Dino container:", dinoContainer.content.name);
console.log("String container:", stringContainer.content);
// Generic interface
interface Repository<T> {
items: T[];
add(item: T): void;
find(predicate: (item: T) => boolean): T | undefined;
getAll(): T[];
}
// Implementation for dinosaurs
class DinosaurRepository implements Repository<Dinosaur> {
items: Dinosaur[] = [];
add(dinosaur: Dinosaur): void {
this.items.push(dinosaur);
console.log(`Added ${dinosaur.name} to repository`);
}
find(predicate: (dinosaur: Dinosaur) => boolean): Dinosaur | undefined {
return this.items.find(predicate);
}
getAll(): Dinosaur[] {
return [...this.items];
}
findByDiet(diet: DinosaurDiet): Dinosaur[] {
return this.items.filter(dino => dino.diet === diet);
}
}
const dinoRepo = new DinosaurRepository();
dinoRepo.add(rexy);
// Generic constraints
interface HasName {
name: string;
}
function logName<T extends HasName>(item: T): T {
console.log(`Logging: ${item.name}`);
return item;
}
logName(rexy); // Works - Dinosaur has name
// logName(123); // Error - number doesn't have name
console.log("Generics work!\n");
// ===========================================
// 6. Utility Types - built-in helper types
// ===========================================
console.log("=== 6. UTILITY TYPES ===");
// Partial - all fields optional
type PartialDinosaur = Partial<Dinosaur>;
function updateDinosaur(dino: Dinosaur, updates: PartialDinosaur): Dinosaur {
return { ...dino, ...updates };
}
const updatedRexy = updateDinosaur(rexy, { isActive: false });
console.log(`${updatedRexy.name} is active: ${updatedRexy.isActive}`);
// Pick - selecting specific fields
type DinosaurSummary = Pick<Dinosaur, "name" | "species" | "dangerLevel">;
function createSummary(dino: Dinosaur): DinosaurSummary {
return {
name: dino.name,
species: dino.species,
dangerLevel: dino.dangerLevel
};
}
const summary = createSummary(rexy);
console.log("Dinosaur summary:", summary);
// Omit - removing specific fields
type PublicDinosaurInfo = Omit<Dinosaur, "id" | "dangerLevel">;
function getPublicInfo(dino: Dinosaur): PublicDinosaurInfo {
const { id, dangerLevel, ...publicInfo } = dino;
return publicInfo;
}
// Record - mapping keys to values
type DinosaurStats = Record<DinosaurDiet, number>;
const dietStats: DinosaurStats = {
carnivore: 3,
herbivore: 7,
omnivore: 2
};
console.log("Diet statistics:", dietStats);
// Required - all fields required
type RequiredDinosaur = Required<Dinosaur>;
console.log("Utility types work!\n");
// ===========================================
// 7. Advanced types
// ===========================================
console.log("=== 7. ADVANCED TYPES ===");
// Mapped types
type ReadonlyDinosaur = {
readonly [K in keyof Dinosaur]: Dinosaur[K];
};
// Conditional types
type DinosaurSound<T> = T extends "carnivore" ? "ROAR" : "HONK";
type TRexSound = DinosaurSound<"carnivore">; // "ROAR"
type TriceratopsSound = DinosaurSound<"herbivore">; // "HONK"
// Template literal types
type EventName<T extends string> = `dinosaur-${T}`;
type DinosaurEvents = EventName<"fed" | "escaped" | "sleeping">;
// Function types
type DinosaurEventHandler = (dinosaur: Dinosaur, event: DinosaurEvents) => void;
const eventHandler: DinosaurEventHandler = (dino, event) => {
console.log(`Event ${event} for ${dino.name}`);
};
eventHandler(rexy, "dinosaur-fed");
console.log("Advanced types work!\n");
// ===========================================
// 8. Practical example - Park management system
// ===========================================
console.log("=== 8. PARK MANAGEMENT SYSTEM ===");
// A complex type system for the park
interface Enclosure {
id: string;
name: string;
capacity: number;
type: "carnivore" | "herbivore" | "mixed";
securityLevel: SecurityLevel;
dinosaurs: Dinosaur[];
isLocked: boolean;
}
interface ParkEvent {
id: string;
timestamp: Date;
type: "feeding" | "escape" | "maintenance" | "visitor";
entityId: string;
severity: "low" | "medium" | "high" | "critical";
message: string;
}
class ParkManager {
private enclosures: Map<string, Enclosure> = new Map();
private eventLog: ParkEvent[] = [];
addEnclosure(enclosure: Omit<Enclosure, "id">): string {
const id = `ENC-${Date.now()}`;
const newEnclosure: Enclosure = { ...enclosure, id };
this.enclosures.set(id, newEnclosure);
this.logEvent({
type: "maintenance",
entityId: id,
severity: "low",
message: `Enclosure ${enclosure.name} created`
});
return id;
}
addDinosaurToEnclosure(dinosaurId: string, enclosureId: string): boolean {
const enclosure = this.enclosures.get(enclosureId);
if (!enclosure) {
console.log("Enclosure not found");
return false;
}
if (enclosure.dinosaurs.length >= enclosure.capacity) {
console.log("Enclosure at capacity");
return false;
}
// In a real application we would fetch the dinosaur from the repository
console.log(`Dinosaur ${dinosaurId} added to ${enclosure.name}`);
return true;
}
private logEvent(event: Omit<ParkEvent, "id" | "timestamp">): void {
const newEvent: ParkEvent = {
...event,
id: `EVT-${Date.now()}`,
timestamp: new Date()
};
this.eventLog.push(newEvent);
}
getEventsByType<T extends ParkEvent["type"]>(type: T): ParkEvent[] {
return this.eventLog.filter(event => event.type === type);
}
getParkStatus(): {
enclosureCount: number;
totalDinosaurs: number;
securityLevel: SecurityLevel;
recentEvents: ParkEvent[];
} {
const enclosures = Array.from(this.enclosures.values());
const totalDinosaurs = enclosures.reduce((sum, enc) => sum + enc.dinosaurs.length, 0);
const maxSecurityLevel = Math.max(...enclosures.map(enc => enc.securityLevel));
return {
enclosureCount: enclosures.length,
totalDinosaurs,
securityLevel: maxSecurityLevel as SecurityLevel,
recentEvents: this.eventLog.slice(-5)
};
}
}
// System test
const parkManager = new ParkManager();
const enclosureId = parkManager.addEnclosure({
name: "T-Rex Paddock",
capacity: 2,
type: "carnivore",
securityLevel: SecurityLevel.Critical,
dinosaurs: [],
isLocked: true
});
parkManager.addDinosaurToEnclosure("rexy", enclosureId);
const status = parkManager.getParkStatus();
console.log("Park status:", status);
console.log("\nTypeScript Park Management System works!\n");
// ===========================================
// 9. TypeScript benefits
// ===========================================
console.log("=== 9. TYPESCRIPT BENEFITS ===");
console.log("TYPE SAFETY:");
console.log(" • Error detection at compile-time");
console.log(" • Preventing common JavaScript errors");
console.log(" • Certainty about data structure\n");
console.log("BETTER TOOLS:");
console.log(" • IntelliSense/autocomplete");
console.log(" • Confident refactoring in the IDE");
console.log(" • Automatic syntax checking\n");
console.log("CODE DOCUMENTATION:");
console.log(" • Types serve as documentation");
console.log(" • Clear API interfaces");
console.log(" • More readable code for the team\n");
console.log("SCALABILITY:");
console.log(" • Easier management of large projects");
console.log(" • Better team collaboration");
console.log(" • Lower risk of regressions\n");
console.log("COMPATIBILITY WITH JAVASCRIPT:");
console.log(" • Gradual migration from JS");
console.log(" • Using JavaScript libraries");
console.log(" • Compiles to plain JS\n");
console.log("TypeScript - safer JavaScript for Jurassic Park!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the most important advantage of TypeScript compared to JavaScript?
2. What is the relationship between TypeScript and JavaScript?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Define a variable dinosaurSpecies of type string and assign it the value 'T-Rex'.