TypeScript extends JavaScript by adding static types. This means you can catch errors during development instead of at runtime. Let's start with the basics: variables and fundamental types.
TypeScript provides several basic types that form the foundation of type-safe code:
// String type
let playerName: string = "Wizard";
let greeting: string = 'Welcome to TypeLand!';
// Number type
let score: number = 100;
let health: number = 75.5;
// Boolean type
let isPlaying: boolean = true;
let hasWon: boolean = false;
// Any type (avoid when possible)
let flexibleValue: any = "could be anything";
flexibleValue = 42; // No error!
TypeScript uses let and const from modern
JavaScript (avoid var in TypeScript):
// let - for variables that can be reassigned
let currentLevel: number = 1;
currentLevel = 2; // ✓ OK
// const - for constants that cannot be reassigned
const maxLives: number = 3;
// maxLives = 5; // ✗ Error: Cannot assign to const
// const with objects (object properties can still change)
const player = {
name: "Hero",
health: 100
};
player.health = 80; // ✓ OK - modifying property
// player = {}; // ✗ Error: Cannot reassign const variable
TypeScript can often infer types automatically, so you don't always need to write explicit type annotations:
// TypeScript infers the type from the initial value
let message = "Hello"; // inferred as string
let count = 10; // inferred as number
let active = true; // inferred as boolean
// message = 42; // ✗ Error: Type 'number' is not assignable to type 'string'
// Explicit annotation is better for clarity sometimes
let unknownValue; // type: any (no inference possible)
let explicitValue: string; // Better: specify the type
let for variables that will change,
const for constants
name: string
any type when possible - it defeats the
purpose of TypeScript
// Define character stats with proper types
const characterName: string = "Aragon";
let characterLevel: number = 5;
let characterHealth: number = 100;
let isAlive: boolean = true;
// Function to take damage
function takeDamage(damage: number): void {
characterHealth -= damage;
if (characterHealth <= 0) {
characterHealth = 0;
isAlive = false;
console.log(`${characterName} has been defeated!`);
} else {
console.log(`${characterName} has ${characterHealth} health remaining.`);
}
}
// Function to heal
function heal(amount: number): void {
if (isAlive) {
characterHealth += amount;
console.log(`${characterName} restored ${amount} health.`);
}
}
// Usage
takeDamage(30); // "Aragon has 70 health remaining."
heal(15); // "Aragon restored 15 health."