The core idea
A type is a promise about what a value can be. A union type is a promise with choices, like "pending" or "paid".
Use basic types for simple values. Use unions when only a few values are valid.
Basic types you use
You will use string, number, boolean, null, undefined, array types, and object shapes often. Lesson 4 will go deeper on object modelling, so keep this lesson focused on small values.
Do not type everything by hand. TypeScript can infer many values. Add types where they make intent clear, especially data coming from forms, APIs, or config.
Simple typed values
This is the kind of code you might have in a hackathon app that tracks orders, events, or project tasks.
let teamName: string = "Code Mandali";
let membersCount: number = 4;
let isSubmitted: boolean = false;
let tags: string[] = ["typescript", "hackathon", "frontend"];
let scores: number[] = [8, 9, 7];
let selectedCoupon: string | null = null;
selectedCoupon = "HACK50";When to use unions
Use a union type when a value can be one of a few known types or labels. This catches spelling mistakes and invalid states before your demo.
A union is made with the pipe symbol. Read string | null as "string or null".
Union for status
Instead of saving any random string as a payment status, list the only allowed values. This fits Indian app flows like UPI payment, event registration, or food ordering.
let paymentStatus: "pending" | "paid" | "failed" = "pending";
paymentStatus = "paid";
// paymentStatus = "done"; // TypeScript error
function statusLabel(status: "pending" | "paid" | "failed") {
if (status === "paid") {
return "Payment received";
}
if (status === "failed") {
return "Payment failed";
}
return "Waiting for payment";
}Do not reach for any
any turns off checking for that value. It is useful only as a short temporary step when converting old JavaScript.
If you use any for form data, API data, or user input, TypeScript cannot help you catch wrong assumptions.
// Weak
let amount: any = "499";
console.log(amount.toFixed(2)); // Breaks at runtime
// Safer
let amountText: string = "499";
let amountInRupees: number = Number(amountText);
console.log(amountInRupees.toFixed(2));Narrow before use
When a value has a union type, check what it is before using methods that only work on one type. This is called narrowing.
AI tools often write code that assumes a value exists. Check for null and undefined in AI-generated code before you copy it.
let phoneNumber: string | undefined = undefined;
if (phoneNumber) {
console.log(phoneNumber.toUpperCase());
} else {
console.log("No phone number added yet");
}Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done