Skip to editor content
learningtypescript.orglesson 2 of 25

Variables and Types

TL;DR — Use const by default; let when you need to reassign. TypeScript's primitive types are string, number, boolean, null, and undefined. Type inference means you can skip annotations when the value makes the type obvious — TypeScript figures it out from what you assign.

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:

  1. Create variables of different types and experiment with type annotations
  2. Try removing type annotations and see how TypeScript infers types
  3. Create an array of strings and access its elements
  4. Use template literals to create formatted output
  5. 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!

Key Takeaways

  • Use let for mutable variables and const for values that never change
  • TypeScript's core types include string, number, boolean, null, undefined, and any
  • Type inference means you don't always need explicit annotations — TypeScript figures it out
  • Union types (string | number) let a variable hold more than one type safely

When your data has more structure than a single variable, you'll want to group types together — see Interfaces and Types for how TypeScript models objects and Type Narrowing for working safely with union types at runtime.

Next Steps

You've learned how to declare variables and annotate them with types. Next, you'll see how to use those types in functions — defining typed parameters, return values, and arrow functions.

Next lesson

Functions

Learn how to write typed functions in TypeScript with optional parameters, overloads, and return types for safer, documented code.

20 min