Basic Types: Classifying Your Data
7 min read
Welcome back, developer! 🚀
In the previous section, we set up our environment. Now, we are going to dive into the core reason TypeScript exists: Types.
If you are coming from JavaScript, you are used to a world of absolute freedom. In JavaScript, a variable can be a number one second, a string the next, and an object ten minutes later. It’s like a party where anyone can walk in.
TypeScript acts as the bouncer. 🛡️ It checks IDs at the door (compile time) so that you don't have a brawl inside the club (runtime).
In this guide, we will cover the "Alphabets" of TypeScript—the fundamental building blocks you need to construct complex applications.
1. Primitive Types: string, number, and boolean
The Definition
Primitive types are the most basic data types available in the language. They represent single values. In TypeScript, the "Big Three" you will use 90% of the time are:
string: Textual data.number: Numeric values (integers, floats, negatives).boolean:trueorfalsevalues.
The Problem
Imagine you are building a calculator app. In JavaScript, you might get input from an HTML form. HTML inputs always return strings.
// JavaScript Reality
const price = "100"; // from input
const tax = 20;
const total = price + tax;
// Result: "10020"
// Why? String concatenation instead of addition. 😱This bug might not crash your app, but it will definitely get you fired from the finance department.
The Solution: Explicit Typing
TypeScript allows us to classify variables the moment we create them.
Syntax: let variableName: type = value;
Let's look at the Big Three in action:
// 1. Strings 🧵
// Use for names, sentences, IDs
let username: string = "FreeCodeCampUser";
let greeting: string = `Hello, ${username}!`; // Template literals work too!
// 2. Numbers 🔢
// Unlike other languages (C/Java), TS doesn't distinguish between int and float.
// Everything is just 'number'.
let userAge: number = 25;
let pi: number = 3.14159;
let negativeBalance: number = -50;
// 3. Booleans 💡
// Use for flags, toggles, conditional logic
let isLoggedIn: boolean = true;
let hasError: boolean = false;Real Life Simulation:
Think of these types like shapes in a toddler's toy sorting box.
- String is the Square hole.
- Number is the Round hole.
- Boolean is the Triangle hole.
If you try to shove a string (Square block) into a variable marked as number (Round hole), TypeScript will yell at you before you even run the code.
let myScore: number = 10;
myScore = "ten"; // Error: Type 'string' is not assignable to type 'number'.Industry Standard Note: Always use lowercase
string,number, andboolean. You might see uppercaseStringorNumberin documentation—those refer to non-primitive wrapper objects in JavaScript and are rarely what you want for typing data.
2. Type Inference: Letting TypeScript Do the Heavy Lifting
The Definition
Type Inference is the compiler's ability to automatically deduce the type of a variable based on the value you assign to it.
The Problem
Writing : type after every single variable is exhausting. It makes the code verbose and harder to read.
// This is correct, but annoying to type 100 times a day
let brandName: string = "Tesla";
let maxSpeed: number = 200;
let isElectric: boolean = true;The Solution
If you assign a value immediately, TypeScript is smart enough to know what type it is. You don't need to tell it.
// TypeScript knows 'brandName' is a string because you gave it a string.
let brandName = "Tesla";
// If you hover over 'brandName' in your editor, you will see 'let brandName: string'If you try to change it later, the protection is still there:
brandName = 42;
// Error: Type 'number' is not assignable to type 'string'.Under the Hood:
When the TypeScript compiler reads your code, it performs "static analysis." It looks at the right side of the = sign, sees "Tesla", and permanently stamps the variable on the left as a string.
When should you use Inference?
- YES: When initializing variables with simple values (
let x = 10). This is the industry standard for clean code. - NO: When you declare a variable now but assign the value later.
// Bad Practice (Implicit 'any')
let score;
score = 10; // TS doesn't know what this was supposed to be originally.
// Good Practice
let score: number;
score = 10;3. The 'any' Type: When to Use It (and Why to Avoid It)
The Definition
any is a specific type in TypeScript that literally means "I don't care what this is, just let it pass." It effectively turns off type checking for that specific variable.
The Problem
Sometimes you are migrating an old JavaScript project to TypeScript. You have a complex object, and you don't have time to write a type definition for it yet. Or, you are using a 3rd party library that doesn't have type definitions.
The Solution (The Escape Hatch)
You can mark a variable as any.
let mysteryData: any = "Could be a string";
mysteryData = 100; // No Error
mysteryData = false; // No Error
mysteryData.flyToMoon(); // No Error (even if the function doesn't exist!)⚠️ The Danger Zone
Using any defeats the purpose of TypeScript. It’s like buying a bulletproof vest and then wearing it properly only on your left arm.
If you use any, you lose compile-time protection and autocomplete features. You are inviting runtime crashes back into your life.
Industry Advice:
- Avoid
anywhenever possible. - If you don't know the type yet, use
unknown(a safer counterpart toanythat forces you to check the type before using it—we'll cover this in advanced topics). - Many rigid ESLint configurations in professional companies will strictly ban the use of
any.
4. Working with Arrays and Tuples
The Definition
- Arrays: A list where all elements are of the same type.
- Tuples: A list of fixed length where each element has a specific type in a specific order.
The Problem
In JavaScript, arrays are dumping grounds.const weirdList = ["Hello", 42, true, { name: "Dog" }];
While flexible, this makes it impossible to know what happens when you loop through the list. If you try to perform math on the list, the strings will crash the calculation.
The Solution A: Typed Arrays
We can specify that an array must only contain specific types.
Syntax: type[]
// A list of grocery items (Strings only)
let groceryList: string[] = ["Eggs", "Milk", "Bread"];
// A list of high scores (Numbers only)
let highScores: number[] = [100, 205, 98];
groceryList.push("Butter"); // ✅ OK
groceryList.push(50); // ❌ Error: Argument of type 'number' is not assignable to parameter of type 'string'.Practical Tip:
You might see Array<number> in some docs. This is called "Generic syntax." It does the exact same thing as number[]. The industry standard (and React convention) prefers number[] for simple lists because it's cleaner to read.
The Solution B: Tuples
Sometimes you need an array that acts like a specific record. For example, a coordinate system (x, y) or a database row (id, name).
Syntax: [type, type]
// Scenario: Storing a User ID and a Username
let userRecord: [number, string];
userRecord = [1, "Admin"]; // ✅ OK
// ❌ Error: Order matters!
userRecord = ["Admin", 1];
// ❌ Error: Too many elements!
userRecord = [1, "Admin", true]; Real Life Use Case:
If you have used React Hooks, useState returns a tuple!const [value, setValue] = useState(0)
The first item is always the value, the second is always the function. TypeScript Tuples enforce this structure.
Summary
We've just cleared the "Alphabets" of TypeScript. Here is your cheat sheet:
- Primitives: Use
string,number,boolean. Lowercase always. - Inference: Let TS guess the type when you assign values immediately (
let x = 10). - Any: The "Disable TS" button. Use with extreme caution. ☢️
- Arrays:
string[]ensures your list stays consistent. - Tuples:
[string, number]ensures fixed order and length.
Did you know? 🤯
TypeScript types are "erased" when you compile the code. If you look at the final JavaScript output, all the : string and : number annotations disappear. They exist purely for the developer experience to help you catch bugs while you type.
Up Next
Now that we know how to classify data, we need to learn how to structure it. In the next section, we will look at Objects and Interfaces.
🔗 References & Further Reading
Challenge
You are building a type-safe data model for a user profile in a new application. Your task is to declare variables for user data, applying the correct TypeScript types based on the requirements below. Do not initialize the variables unless explicitly instructed.
- Declare a variable
userIdto store a unique numeric identifier. - Declare a variable
usernameto store the user's name. - Declare a variable
isActiveto store the user's account status (trueorfalse). - Declare a variable
userRolesto store a list of roles. This list must only contain strings. - Declare a variable
userAuththat will store a fixed-size list containing the user's numeric ID followed by their string username. The order and types must be strictly enforced. - Declare a variable
lastLoginfor a future timestamp. It is not assigned a value yet, but it must be explicitly typed to hold a number. - Finally, declare a variable
appThemeand initialize it with the value'dark'. You should not add an explicit type annotation; let TypeScript infer its type.
Expected result
Your code should correctly declare seven variables with the appropriate TypeScript type annotations based on the instructions.
userIdshould be explicitly typed as anumber.usernameshould be explicitly typed as astring.isActiveshould be explicitly typed as aboolean.userRolesshould be typed as an array of strings, using thestring[]syntax.userAuthshould be typed as a tuple that accepts anumberas its first element and astringas its second, using[number, string]syntax.lastLoginshould be explicitly typed as anumberwithout an initial value.appThemeshould be declared and initialized in a way that allows TypeScript to infer its type asstring, without any explicit type annotation.
Example of a correct solution:
let userId: number;
let username: string;
let isActive: boolean;
let userRoles: string[];
let userAuth: [number, string];
let lastLogin: number;
let appTheme = 'dark';