Basic Data Types

TypeScript provides type annotations to explicitly define primitive data types and special safety types.

1. Primitive Types

TypeDescriptionCode Example
numberIntegers, floats, hexadecimal, binary valueslet count: number = 42;
stringTextual data, template literalslet name: string = "Alice";
booleanTrue or false valueslet isActive: boolean = true;

2. Type Inference

You don't always have to write explicit types! TypeScript automatically infers the variable type based on its initial value:

// TypeScript automatically infers message as string
let message = "Hello World";

// ❌ Error: Type 'number' is not assignable to type 'string'
message = 123;

3. `any` vs `unknown` (Type Safety Comparison)

Both any and unknown accept any value, but unknown is type-safe because it forces you to perform type checking before performing operations!

`any` (Disables Type Checking):
let data: any = "Hello";
data.toUpperCase(); // OK
data(); // 💥 Crashes at runtime!
`unknown` (Type-Safe Escape Hatch):
let data: unknown = "Hello";

// ❌ Error: Property 'toUpperCase' does not exist on type 'unknown'
// data.toUpperCase();

if (typeof data === "string") {
  console.log(data.toUpperCase()); // Safe!
}

4. `void` vs `never`

// void: Function returns nothing (undefined)
function logMessage(msg: string): void {
  console.log(msg);
}

// never: Function NEVER returns (throws error or infinite loop)
function throwError(errorMsg: string): never {
  throw new Error(errorMsg);
}

Next Up

Learn typed arrays, fixed-length tuples, and readonly arrays in TypeScript.

Next Lesson: Arrays & Tuples →