#typescript #beginner #types

Day 2: Primitive Types: The Building Blocks

The Foundation of TypeScript

Welcome to Day 2! Yesterday, we set up our environment and wrote our first “Hello World” program. Today, we’re diving into the core of TypeScript: Primitive Types.

In JavaScript, we have primitive types like string, number, and boolean, but they are dynamic. In TypeScript, we lock them down to prevent silly mistakes.

The Big Three: String, Number, Boolean

These are the most common types you’ll use.

1. String

Used for text data. You can use single quotes, double quotes, or backticks (template literals).

let firstName: string = "Jack";
let greeting: string = `Hello, ${firstName}`; // Template literal

2. Number

TypeScript doesn’t have int or float. Everything is just number. This includes integers, floating-point values, hex, binary, and octal literals.

let age: number = 25;
let price: number = 99.99;
let hex: number = 0xf00d;

3. Boolean

True or false values.

let isLoggedIn: boolean = true;
let hasError: boolean = false;

Type Inference vs. Type Annotation

You might have noticed that sometimes we don’t need to write the type.

Type Annotation

This is when we explicitly tell TypeScript what the type is.

let score: number = 100;

Type Inference

TypeScript is smart. If you initialize a variable with a number, it infers that it is a number.

let score = 100; // TypeScript knows this is a number
// score = "high"; // Error!

Best Practice: Use type inference where possible to keep your code clean. Use annotations when:

  • You declare a variable without a value.
  • You want to ensure a specific type that might not be inferred correctly.
  • You are defining function parameters (more on that later).

Two Special Types: null and undefined

In TypeScript, null and undefined are actual types.

let n: null = null;
let u: undefined = undefined;

By default, null and undefined are subtypes of all other types (unless you have strictNullChecks on, which you should!). If strictNullChecks is on (default in modern TypeScript), you can’t assign null to a string.

Challenge for Today

  1. Create a file day2.ts.
  2. Declare variables for your name (string), age (number), and isStudent (boolean).
  3. Try to assign a number to your name variable and see the error.
  4. Print a sentence using all three variables (e.g., “My name is Jack, I am 25, and it is true that I am a student.”).

See you on Day 3, where we’ll tackle Arrays and Tuples!