← Back to all tutorials

Type Basics

Core TypeScript types — string, number, boolean — and how type inference works.

Type Basics

TypeScript has the same basic types as JavaScript, but makes them explicit and enforceable.

The Basic Types

let name: string = "Mario";
let age: number = 30;
let isActive: boolean = true;

Type Inference

You don't always need to annotate types. TypeScript infers them from values:

let title = "TypeScript";  // inferred as string
let count = 42;            // inferred as number
let done = false;          // inferred as boolean

title = 100;  // ❌ Error!

Functions & Type Inference

const diameter = 10;

// TypeScript infers the return type as number
const circumference = diameter * Math.PI;

// With explicit parameter types
const add = (a: number, b: number) => {
    return a + b;  // return type inferred as number
};

Type Errors vs Runtime Errors

TypeScript catches errors before your code runs:

let greeting = "Hello";
console.log(greeting.push("!")); 
// ❌ Compile error: Property 'push' does not exist on type 'string'
// In JS, this would be a runtime error

Key Takeaways

  • Core types: string, number, boolean
  • TypeScript infers types from assigned values
  • Once inferred, types can't be changed
  • Errors are caught at compile time, not runtime