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
- Create a file
day2.ts. - Declare variables for your
name(string),age(number), andisStudent(boolean). - Try to assign a number to your
namevariable and see the error. - 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!