Variables and Types
In this lesson, we'll explore how TypeScript handles variables and its type system. You'll learn about variable declaration, type annotations, and the most common types you'll use in your TypeScript programs.
Variable Declaration
TypeScript supports three ways to declare variables, each with different scoping rules:
// const: Cannot be reassigned (use this by default)
const x = 5;
console.log(`x is ${x}`);
// let: Can be reassigned, block-scoped
let y = 10;
console.log(`y is ${y}`);
y = 15;
console.log(`y is now ${y}`);
// var: Function-scoped (avoid using this - it's from old JavaScript)
var z = 20;
console.log(`z is ${z}`);
Type Annotations
TypeScript allows you to explicitly specify types for your variables:
// Explicit type annotations
const name: string = "Alice";
const age: number = 30;
const isStudent: boolean = true;
console.log(`${name} is ${age} years old`);
console.log(`Is student: ${isStudent}`);
Basic Types
TypeScript provides several built-in types to work with:
Primitive Types
String
const greeting: string = "Hello, TypeScript!";
const template: string = `This is a template literal`;
console.log(greeting);
console.log(template);
Number
// TypeScript has only one number type (no separate int/float)
const integer: number = 42;
const float: number = 3.14;
const negative: number = -10;
const hex: number = 0xf00d;
console.log(`Integer: ${integer}`);
console.log(`Float: ${float}`);
console.log(`Negative: ${negative}`);
console.log(`Hex: ${hex}`);
Boolean
const isTrue: boolean = true;
const isFalse: boolean = false;
console.log(`True: ${isTrue}, False: ${isFalse}`);
Special Types
Any
// any disables type checking (use sparingly!)
let anything: any = "a string";
anything = 42;
anything = true;
console.log(`anything can be: ${anything}`);
Unknown
// unknown is a type-safe alternative to any
let uncertain: unknown = "some value";
// You must check the type before using it
if (typeof uncertain === "string") {
console.log(`uncertain is a string: ${uncertain}`);
}
Null and Undefined
const empty: null = null;
const notDefined: undefined = undefined;
console.log(`Null: ${empty}, Undefined: ${notDefined}`);
Type Inference
TypeScript can automatically infer types based on the assigned value:
// TypeScript infers these types automatically
const inferredString = "Hello"; // type: string
const inferredNumber = 42; // type: number
const inferredBoolean = true; // type: boolean
console.log(`Inferred string: ${inferredString}`);
console.log(`Inferred number: ${inferredNumber}`);
console.log(`Inferred boolean: ${inferredBoolean}`);
// Type inference works with arrays too
const numbers = [1, 2, 3, 4, 5]; // type: number[]
const mixed = [1, "two", 3]; // type: (string | number)[]
console.log(`Numbers: ${numbers}`);
console.log(`Mixed: ${mixed}`);
Type Assertions
Sometimes you know more about a value's type than TypeScript does:
// Type assertion using 'as'
const someValue: unknown = "this is a string";
const stringLength: number = (someValue as string).length;
console.log(`String length: ${stringLength}`);
Literal Types
You can use specific literal values as types:
// Literal types
const constantString: "hello" = "hello";
const constantNumber: 42 = 42;
const constantBoolean: true = true;
console.log(`Literals: ${constantString}, ${constantNumber}, ${constantBoolean}`);
Try It Yourself
Practice using different types in the playground below:
// Create variables with different types
const username: string = "Alice";
const score: number = 95.5;
const isPassing: boolean = score >= 60;
console.log(`Student: ${username}`);
console.log(`Score: ${score}`);
console.log(`Passing: ${isPassing}`);
// Type inference example
const colors = ["red", "green", "blue"];
const firstColor = colors[0];
console.log(`Colors: ${colors}`);
console.log(`First color: ${firstColor}`);
// Working with numbers
const a = 10;
const b = 20;
const sum = a + b;
console.log(`${a} + ${b} = ${sum}`);
Try these exercises:
- Create variables of different types and experiment with type annotations
- Try removing type annotations and see how TypeScript infers types
- Create an array of strings and access its elements
- Use template literals to create formatted output
- Try assigning a value of the wrong type and observe the error
Remember: TypeScript's type system helps catch errors before your code runs. Use type annotations when they make your code clearer, and let TypeScript infer types when it's obvious!