TypeScript Simple Types
Understanding basic data types in TypeScript
🔤 What are Simple Types?
TypeScript simple types define what kind of data a variable can hold. The three main types are string (text), number (numeric values), and boolean (true/false). These types help catch errors early.
// Simple type examples
let userName: string = "John";
let age: number = 25;
let isStudent: boolean = true;
Output:
userName: "John"
age: 25
isStudent: true
Three Main Simple Types
String
For text and characters
let name: string = "Alice";
let greeting: string = 'Hello';
Number
For all numeric values
let count: number = 42;
let price: number = 19.99;
Boolean
For true or false values
let isActive: boolean = true;
let hasAccess: boolean = false;
🔹 String Type
Strings represent text data. Use single quotes, double quotes, or backticks:
// Different ways to declare strings
let firstName: string = "John";
let lastName: string = 'Doe';
let fullName: string = `${firstName} ${lastName}`;
console.log(fullName); // Output: John Doe
Output:
John Doe
🔹 Number Type
Numbers include integers, decimals, and special numeric values:
// All numbers use the same type
let integer: number = 100;
let decimal: number = 3.14;
let negative: number = -50;
let hex: number = 0xFF; // Hexadecimal
console.log(integer + decimal); // Output: 103.14
Output:
103.14
🔹 Boolean Type
Booleans have only two values: true or false:
// Boolean examples
let isLoggedIn: boolean = true;
let hasPermission: boolean = false;
if (isLoggedIn) {
console.log("Welcome back!");
}
Output:
Welcome back!
🔹 Type Safety in Action
TypeScript prevents type errors at compile time:
// ✅ Correct usage
let score: number = 100;
score = 200; // OK
// ❌ Type error
let username: string = "Alice";
// username = 123; // Error: Type 'number' is not assignable to type 'string'
// ✅ Correct type
username = "Bob"; // OK
💡 Why Use Types?
- Catch errors before running code
- Better code editor suggestions
- Makes code easier to understand
- Prevents common mistakes
🔹 Practical Example
Using simple types together in a real scenario:
// User profile with simple types
let userId: number = 12345;
let userName: string = "Sarah";
let isAdmin: boolean = false;
let accountBalance: number = 1250.50;
console.log(`User: ${userName} (ID: ${userId})`);
console.log(`Admin: ${isAdmin}`);
console.log(`Balance: $${accountBalance}`);
Output:
User: Sarah (ID: 12345)
Admin: false
Balance: $1250.5