JavaScript and TypeScript course · Module 6: TypeScript Basics

Basic types (string, number, boolean, any, unknown)

7 min read ·
In this lesson12

Welcome back to our journey through TypeScript in Jurassic Park! Today Dr. Henry Wu has a special lesson for you. Just as categorizing dinosaur species is crucial for their proper breeding and care, categorizing data in TypeScript is a fundamental element of writing safe code.

Why are types important?

Without proper categorization, chaos would quickly spread through Jurassic Park - imagine feeding predators herbivore food, or placing small, gentle species in enclosures with large predators.

In programming, types play a similar role - they prevent "mixing species" of data that shouldn't be mixed. Let's look at the basic data types in TypeScript, using examples related to park management.

String - character strings

The string type in TypeScript represents text - species names, descriptions, identifiers and other textual data.

// Declaring string type variables
let speciesName: string = "Tyrannosaurus Rex";
let dnaCode: string = "ACGTTGCA";
let enclosureCode: string = "P-12";

// String operations
let fullDescription: string = `${speciesName} (DNA code: ${dnaCode}) - enclosure ${enclosureCode}`;
console.log(fullDescription.toUpperCase()); // Displays: "TYRANNOSAURUS REX (DNA CODE: ACGTTGCA) - ENCLOSURE P-12"

Number - numbers

The number type handles both integers and floating-point numbers. It's ideal for representing dinosaur ages, their weights, the park budget and other numeric values.

// Declaring number type variables
let dinosaurAge: number = 5; // in years
let dinosaurWeight: number = 7500.5; // in kilograms
let bodyTemperature: number = 38.2; // in degrees Celsius

// Mathematical operations
let dailyFoodRation: number = dinosaurWeight * 0.05; // 5% of weight daily
let annualMaintenanceCost: number = dailyFoodRation * 365 * 10; // food cost in dollars

Boolean - logical values

The boolean type represents true/false values, ideal for tracking statuses, conditions or flags in the park system.

// Declaring boolean type variables
let isPredator: boolean = true;
let isActive: boolean = false;
let isAdult: boolean = dinosaurAge >= 3; // calculated value

// Use in conditional logic
if (isPredator && isActive) {
  console.log("WARNING: Active predator! Check enclosure security!");
}

// Use in a configuration object
let securityProtocol = {
  requiresDoubleEnclosure: isPredator,
  requiresNightMonitoring: isActive,
  allowedForVisitors: !isPredator || !isActive
};

Any - any type

The any type is like an unknown dinosaur species that can behave unpredictably. It allows assigning any value to a variable and performing any operations on it - which can be dangerous!

// Declaring any type variables
let researchSample: any = "DNA-123";
researchSample = 42; // We can change the type to number
researchSample = true; // We can change the type to boolean
researchSample = { type: "blood", age: "unknown" }; // We can change the type to object

// Dangerous operations
researchSample.nonExistentMethod(); // TypeScript won't report an error!

WARNING: Dr. Wu strongly advises against overusing the any type - it's like letting unidentified dinosaurs into the park without proper security! Use it only as a last resort when you truly don't know what type of data you'll receive.

Unknown - unknown type, but safer

The unknown type is like a new dinosaur species in quarantine - before you release it, you must carefully check its properties.

// Declaring unknown type variables
let newDiscovery: unknown = fetchDataFromExcavation();

// We can't perform operations directly
// newDiscovery.method(); // Error: Object is of type 'unknown'

// We must first check the type
if (typeof newDiscovery === "string") {
  console.log(newDiscovery.toUpperCase()); // OK
} else if (typeof newDiscovery === "number") {
  console.log(newDiscovery.toFixed(2)); // OK
} else if (newDiscovery instanceof DinoFragment) {
  console.log(newDiscovery.analyzeDNA()); // OK
}

Literal types - restricting values

Literal types allow defining a strict set of allowed values, which is useful for example when defining dinosaur species or security zones.

// Literal types
type PredatorSpecies = "Tyrannosaurus" | "Velociraptor" | "Spinosaurus";
type ThreatLevel = 1 | 2 | 3 | 4 | 5;
type EnclosureStatus = "active" | "under maintenance" | "closed";

// Using literal types
let currentPredator: PredatorSpecies = "Velociraptor";
let threat: ThreatLevel = 4;
let tEnclosureStatus: EnclosureStatus = "active";

// Attempting to assign a disallowed value will cause an error
// currentPredator = "Stegosaurus"; // Error: Type '"Stegosaurus"' is not assignable to type 'PredatorSpecies'

Type Inference - automatic type detection

TypeScript can automatically infer the type of a variable based on its assigned value, allowing for more concise code.

// Automatic type detection
let dinoName = "Blue"; // TypeScript infers type string
let age = 3; // TypeScript infers type number
let isActive = true; // TypeScript infers type boolean

// TypeScript prevents incorrect assignment
// dinoName = 42; // Error: Type 'number' is not assignable to type 'string'

Union Types - union types

Union types allow specifying that a variable can take values of several different types, which is useful in many park scenarios.

// Declaring a variable that can be string or number
let identifier: string | number;

identifier = "TREX-001"; // OK
identifier = 12345; // OK
// identifier = true; // Error: Type 'boolean' is not assignable to type 'string | number'

// Function handling different dinosaur data types
function processData(data: string | number | boolean) {
  if (typeof data === "string") {
    return data.toUpperCase();
  } else if (typeof data === "number") {
    return data.toFixed(2);
  } else {
    return data ? "ACTIVE" : "INACTIVE";
  }
}

Null and Undefined

In TypeScript, null and undefined are special values that can be useful for representing the absence of data, for example when a dinosaur hasn't received an RFID tag yet.

// With strictNullChecks enabled in tsconfig.json
let rfidTag: string | null = null; // Dinosaur hasn't received a tag yet
let lastCheckup: Date | undefined; // Checkup hasn't been performed yet

// Checking before use
function checkStatus(dino: { name: string, tag: string | null }) {
  if (dino.tag === null) {
    return `${dino.name} has no RFID tag - requires tagging`;
  } else {
    return `${dino.name} tagged with ${dino.tag}`;
  }
}

Practical application of basic types

Let's consider a dinosaur health monitoring system where we use different data types:

// Interface describing the structure of dinosaur data
interface DinosaurData {
  id: number;
  name: string;
  species: string;
  age: number;
  weight: number;
  isPredator: boolean;
  healthStatus: "good" | "fair" | "needs attention" | "critical" | null;
  rfidTag: string | null;
  lastCheckup: Date | undefined;
}

// Function checking whether a dinosaur needs veterinary intervention
function needsIntervention(dino: DinosaurData): boolean {
  // A dinosaur needs intervention if:
  // - its health status is critical
  // - it hasn't had a checkup in the last 30 days
  // - it has no RFID tag

  const today = new Date();
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(today.getDate() - 30);

  return (
    dino.healthStatus === "critical" ||
    dino.healthStatus === null ||
    dino.rfidTag === null ||
    (dino.lastCheckup === undefined || dino.lastCheckup < thirtyDaysAgo)
  );
}

// Example usage
const raptorBlue: DinosaurData = {
  id: 101,
  name: "Blue",
  species: "Velociraptor",
  age: 5,
  weight: 350,
  isPredator: true,
  healthStatus: "good",
  rfidTag: "VR-101-BLUE",
  lastCheckup: new Date("2023-08-15")
};

const trixie: DinosaurData = {
  id: 205,
  name: "Trixie",
  species: "Triceratops",
  age: 12,
  weight: 8500,
  isPredator: false,
  healthStatus: "needs attention",
  rfidTag: "TC-205-TRIXIE",
  lastCheckup: undefined
};

console.log(`Blue needs intervention: ${needsIntervention(raptorBlue)}`);
console.log(`Trixie needs intervention: ${needsIntervention(trixie)}`);

Summary

Proper use of basic types in TypeScript is like precisely managing different dinosaur species in Jurassic Park - it ensures safety and predictability.

TypeUse in Jurassic ParkExample
stringNames, descriptions, identifiers"Velociraptor", "P-12"
numberAge, weight, costs5, 7500.5, 38.2
booleanStatuses, conditions, flagstrue, false
anyData of unknown structure (use with caution!)Legacy systems, external data
unknownSafer alternative to anyData requiring validation
union typesValues that can be of different typesstringnumbernull
literal typesRestricted set of values"active""inactive"

In the next lesson we'll look at more complex types such as arrays, tuples and enumerations, which will allow us to model the structure of our park data even better.

Dr. Henry Wu reminds us: "Just as in dinosaur genetics, in TypeScript precision of types is the key to success and avoiding... surprises."

Code for this lesson: index.ts
// Basic types in Jurassic Park
console.log("Basic TypeScript types\n");

// ===========================================
// 1. STRING - text
// ===========================================
console.log("=== STRING TYPE ===");

let species: string = "Tyrannosaurus Rex";
let dnaCode: string = "ACGTTGCA";
let paddockId: string = "P-12";

// Template literals
let fullDescription: string = `${species} (DNA: ${dnaCode}) - Paddock ${paddockId}`;
console.log(fullDescription);
console.log(`Uppercase: ${species.toUpperCase()}`);

// ===========================================
// 2. NUMBER - numbers
// ===========================================
console.log("\n=== NUMBER TYPE ===");

let age: number = 5; // years
let weight: number = 7500.5; // kg
let temperature: number = 38.2; // °C
let hexValue: number = 0xFF; // 255
let binaryValue: number = 0b1010; // 10

console.log(`Age: ${age} years`);
console.log(`Weight: ${weight}kg`);
console.log(`Temperature: ${temperature}°C`);

// Mathematical operations
let dailyFeed: number = weight * 0.05;
let yearlyFeedCost: number = dailyFeed * 365 * 10;
console.log(`Daily feed: ${dailyFeed}kg`);
console.log(`Yearly cost: $${yearlyFeedCost}`);

// ===========================================
// 3. BOOLEAN - logical values
// ===========================================
console.log("\n=== BOOLEAN TYPE ===");

let isCarnivore: boolean = true;
let isActive: boolean = false;
let isAdult: boolean = age >= 3;
let isHungry: boolean = true;
let isDangerous: boolean = isCarnivore && isHungry;

console.log(`Is carnivore: ${isCarnivore}`);
console.log(`Is active: ${isActive}`);
console.log(`Is adult: ${isAdult}`);
console.log(`Is dangerous: ${isDangerous}`);

// Conditional logic
if (isDangerous) {
  console.log("Security level: CRITICAL");
} else {
  console.log("Security level: NORMAL");
}

// ===========================================
// 4. ANY - any type (avoid it!)
// ===========================================
console.log("\n=== ANY TYPE ===");

let mysteryData: any = "unknown";
mysteryData = 123; // OK
mysteryData = true; // OK
mysteryData = { type: "fossil" }; // OK

console.log("ANY doesn't check types - use carefully!");
console.log("Mystery data:", mysteryData);

// ===========================================
// 5. UNKNOWN - a safer any
// ===========================================
console.log("\n=== UNKNOWN TYPE ===");

let unknownData: unknown = "mysterious DNA sequence";

// We must check the type before use
if (typeof unknownData === 'string') {
  console.log("Unknown data length:", unknownData.length);
} else {
  console.log("Not a string");
}

console.log("UNKNOWN requires a type check");

// ===========================================
// 6. NULL and UNDEFINED
// ===========================================
console.log("\n=== NULL AND UNDEFINED ===");

let emptyValue: null = null;
let notInitialized: undefined = undefined;

let optionalSpecies: string | null = null; // can be string or null
let optionalAge: number | undefined; // can be number or undefined

console.log("Empty value:", emptyValue);
console.log("Not initialized:", notInitialized);
console.log("Optional species:", optionalSpecies);
console.log("Optional age:", optionalAge);

// Checking for null/undefined
function displaySpecies(s: string | null): void {
  if (s !== null) {
    console.log(`Species: ${s}`);
  } else {
    console.log("Species unknown");
  }
}

displaySpecies(species);
displaySpecies(null);

// ===========================================
// 7. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("string - text and characters");
console.log("number - numbers (int, float, hex, binary)");
console.log("boolean - true/false");
console.log("any - any type (avoid it)");
console.log("unknown - a safer any");
console.log("null - no value");
console.log("undefined - not initialized");

console.log("\nBasic types mastered!");

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. 1. What does the : operator after a variable name do in TypeScript?

Hands-on tasks in the game

  • Code editor

    Define variables with string, number, and boolean types describing a dinosaur.

  • Horizontal ordering

    Arrange the elements of a typed variable declaration in TypeScript:

  • Click in order

    Arrange the elements of a TypeScript function with types:

  1. QuestionType Annotation
  2. Coding taskPractice: Basic Types
  3. Put in orderType Annotation Syntax
  4. Click in orderSorting: Function Type Annotation

Useful articles