From Zero to AI

Lesson 3.1: Basic Types

Duration: 50 minutes

Learning Objectives

By the end of this lesson, you will be able to:

  • Use the primitive types: string, number, and boolean
  • Work with arrays in TypeScript
  • Understand null, undefined, and when to use them
  • Recognize the any type and why to avoid it

The Foundation: Primitive Types

TypeScript has three main primitive types that you will use constantly. These are the same types JavaScript has, but TypeScript lets you explicitly declare them.

string

Strings hold text data. In TypeScript, you declare a string variable like this:

let firstName: string = 'Alice';
let greeting: string = 'Hello, World!';
let template: string = `Welcome, ${firstName}!`;

All three quote styles work: double quotes, single quotes, and backticks (template literals).

// TypeScript catches errors
let name: string = 'Bob';
name = 42; // Error! Type 'number' is not assignable to type 'string'

number

Numbers in TypeScript include integers, decimals, and special numeric values:

let age: number = 25;
let price: number = 19.99;
let negative: number = -10;
let hex: number = 0xff; // Hexadecimal (255)
let binary: number = 0b1010; // Binary (10)
let infinity: number = Infinity;

Unlike some languages, TypeScript does not distinguish between integers and floating-point numbers. They are all number.

let count: number = 100;
count = 'one hundred'; // Error! Type 'string' is not assignable to type 'number'

boolean

Booleans represent true/false values:

let isActive: boolean = true;
let hasPermission: boolean = false;
let isLoggedIn: boolean = true;

Booleans are essential for conditions and flags:

let isAdmin: boolean = true;

if (isAdmin) {
  console.log('Welcome, administrator!');
}

Working with Arrays

Arrays hold multiple values of the same type. TypeScript has two syntaxes for array types:

Syntax 1: Type with Square Brackets

let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ['Alice', 'Bob', 'Charlie'];
let flags: boolean[] = [true, false, true];

Syntax 2: Generic Array Type

let numbers: Array<number> = [1, 2, 3, 4, 5];
let names: Array<string> = ['Alice', 'Bob', 'Charlie'];

Both syntaxes are equivalent. The first (number[]) is more common.

TypeScript Protects Your Arrays

let scores: number[] = [90, 85, 92];

scores.push(88); // OK - adding a number
scores.push('A+'); // Error! Argument of type 'string' is not assignable to parameter of type 'number'

scores[0] = 95; // OK - replacing with a number
scores[0] = 'ninety'; // Error! Type 'string' is not assignable to type 'number'

Empty Arrays Need Type Annotations

When you create an empty array, TypeScript cannot infer the type:

// Without annotation, TypeScript assumes 'any[]'
let items = []; // Type is any[] - not helpful!

// With annotation, TypeScript knows what to expect
let items: string[] = [];
items.push("apple");  // OK
items.push(42);       // Error! Argument of type 'number' is not assignable

Special Types: null and undefined

JavaScript has two "empty" values: null and undefined. TypeScript treats them as distinct types.

undefined

A variable is undefined when it has been declared but not assigned a value:

let notAssigned: undefined = undefined;

// More commonly seen with optional values
let middleName: string | undefined = undefined;

null

null represents an intentional absence of value:

let emptyValue: null = null;

// More commonly used with objects
let user: { name: string } | null = null;

When to Use Each

  • Use undefined for uninitialized or optional values
  • Use null for intentionally empty values
  • Many developers prefer undefined for consistency
// Optional parameter - uses undefined
function greet(name?: string) {
  if (name === undefined) {
    console.log('Hello, stranger!');
  } else {
    console.log(`Hello, ${name}!`);
  }
}

// Nullable return - uses null
function findUser(id: number): { name: string } | null {
  // Returns null if user not found
  return null;
}

The any Type: Use with Caution

The any type disables type checking for a variable:

let anything: any = 'hello';
anything = 42; // OK
anything = true; // OK
anything = [1, 2, 3]; // OK

Why any Exists

Sometimes you are working with data whose type you genuinely do not know, such as:

  • Data from external APIs before validation
  • Migration from JavaScript to TypeScript
  • Third-party libraries without type definitions

Why to Avoid any

Using any defeats the purpose of TypeScript:

let data: any = 'hello';

// TypeScript cannot help you here
console.log(data.toFixed(2)); // No error! But crashes at runtime
// (strings don't have toFixed)

Better Alternatives

Instead of any, consider:

// unknown - safer than any, forces type checking
let data: unknown = getUserInput();
if (typeof data === 'string') {
  console.log(data.toUpperCase()); // OK - TypeScript knows it's a string
}

// Union types - when value can be several specific types
let id: string | number = 'user_123';
id = 456; // Also OK

Type Inference Preview

You may have noticed that we do not always need to write the type:

// Explicit type annotation
let message: string = "Hello";

// TypeScript infers the type from the value
let message = "Hello"; // TypeScript knows this is a string

We will cover type inference in detail in the next lesson.


Practical Examples

Example 1: User Profile Data

let username: string = 'alice_dev';
let age: number = 28;
let isPremium: boolean = false;
let interests: string[] = ['coding', 'gaming', 'music'];

console.log(`${username} is ${age} years old`);
console.log(`Premium member: ${isPremium}`);
console.log(`Interests: ${interests.join(', ')}`);

Example 2: Shopping Cart Item

let productName: string = 'Wireless Mouse';
let price: number = 29.99;
let quantity: number = 2;
let inStock: boolean = true;

let total: number = price * quantity;
console.log(`${productName}: $${total}`);

Example 3: Quiz Scores

let studentName: string = 'Bob';
let scores: number[] = [85, 92, 78, 96, 88];

// Calculate average
let sum: number = 0;
for (let score of scores) {
  sum = sum + score;
}
let average: number = sum / scores.length;

console.log(`${studentName}'s average: ${average.toFixed(1)}`);

Exercises

Exercise 1: Variable Types

Declare variables with appropriate types for:

  • A person's full name
  • Their height in centimeters
  • Whether they have a driver's license
  • A list of their favorite movies
Solution
let fullName: string = 'John Smith';
let heightCm: number = 175;
let hasDriversLicense: boolean = true;
let favoriteMovies: string[] = ['Inception', 'The Matrix', 'Interstellar'];

console.log(`${fullName} is ${heightCm}cm tall`);
console.log(`Has license: ${hasDriversLicense}`);
console.log(`Favorite movies: ${favoriteMovies.join(', ')}`);

Exercise 2: Fix the Type Errors

This code has type errors. Find and fix them:

let temperature: string = 72;
let isRaining: number = false;
let cities: boolean[] = ['Paris', 'London', 'Tokyo'];
let population: string = 1000000;
Solution
let temperature: number = 72;
let isRaining: boolean = false;
let cities: string[] = ['Paris', 'London', 'Tokyo'];
let population: number = 1000000;

Exercise 3: Array Operations

Create a typed array of numbers, then:

  1. Add a new number
  2. Calculate the sum
  3. Find the largest number
Solution
let numbers: number[] = [10, 25, 8, 42, 15];

// Add a new number
numbers.push(30);

// Calculate sum
let sum: number = 0;
for (let num of numbers) {
  sum = sum + num;
}
console.log(`Sum: ${sum}`); // 130

// Find largest
let largest: number = numbers[0];
for (let num of numbers) {
  if (num > largest) {
    largest = num;
  }
}
console.log(`Largest: ${largest}`); // 42

Exercise 4: Avoiding any

Rewrite this code to use proper types instead of any:

let userId: any = 'user_123';
let isActive: any = true;
let loginCount: any = 5;
let tags: any = ['admin', 'verified'];
Solution
let userId: string = 'user_123';
let isActive: boolean = true;
let loginCount: number = 5;
let tags: string[] = ['admin', 'verified'];

Key Takeaways

  1. Three primitive types: string, number, boolean are the foundation
  2. Arrays use type[]: Declare arrays with the element type followed by brackets
  3. null and undefined: Two different "empty" values with distinct meanings
  4. Avoid any: It disables TypeScript's protection - use specific types instead
  5. Type annotations follow the colon: variable: type = value
  6. TypeScript prevents type mixing: You cannot assign a string to a number variable

Resources

Resource Type Description
TypeScript Handbook: Everyday Types Documentation Official guide to basic types
TypeScript Playground Tool Try code examples online
MDN: JavaScript Data Types Documentation Understanding the underlying JavaScript types

Next Lesson

Now that you know the basic types, let us explore when TypeScript can figure out types automatically and when you need to specify them explicitly.

Continue to Lesson 3.2: Type Annotations vs Inference