Primitive Types Unions and Type Aliases
Annotate variables with string, number, boolean, and arrays. Create union types with | and give them readable names with type aliases.
Primitive Types Unions and Type Aliases is a free Frontend Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Annotating Variables
Add type annotations with a colon after the variable name. TypeScript infers types when possible — add explicit annotations where inference is unclear or for documentation.
let score: number = 0;
const greeting: string = 'Hello';
let active: boolean = true;
let data: null = null;
let placeholder: undefined;
// Inferred (no annotation needed):
const pi = 3.14; // TypeScript knows this is numberPrimitive Types
TypeScript's primitive types map to JavaScript's primitives: string, number (no integer/float distinction), boolean, null, undefined, symbol, bigint.
function greet(name: string): string {
return `Hello, ${name}`;
}
function double(n: number): number {
return n * 2;
}
function toggle(active: boolean): boolean {
return !active;
}Arrays
Type an array with Type[] or the generic Array<Type>. Both are equivalent.
const names: string[] = ['Alice', 'Bob'];
const scores: number[] = [98, 87, 72];
const flags: boolean[] = [true, false, true];
// Generic syntax:
const items: Array<string> = ['a', 'b'];Union Types: |
Union types allow a variable to hold one of several types. Use the pipe | operator. TypeScript narrows the type inside conditionals.
function formatId(id: number | string): string {
if (typeof id === 'number') {
return `#${id.toString().padStart(6, '0')}`; // id is narrowed to number
}
return id.toUpperCase(); // id is narrowed to string
}Literal Types
You can use literal string, number, or boolean values as types. Combined with unions, they create a fixed set of allowed values — like an enum.
type Direction = 'north' | 'south' | 'east' | 'west';
type Status = 'pending' | 'active' | 'cancelled';
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
function move(dir: Direction) { /* ... */ }
move('north'); // OK
move('up'); // Error: Argument not assignableType Aliases: type
The type keyword creates a type alias — a reusable name for any type. Aliases work for primitives, unions, objects, tuples, and complex composed types.
type UserId = string | number;
type RGB = [number, number, number]; // tuple
type Callback = (event: MouseEvent) => void;
const userId: UserId = 42;
const red: RGB = [255, 0, 0];
const handler: Callback = (e) => console.log(e.type);Object Types with type
Describe object shapes with type aliases. Mark properties optional with ? and readonly with readonly.
type User = {
id: number;
name: string;
email: string;
role?: 'admin' | 'user'; // optional
readonly createdAt: Date; // can't reassign
};
const user: User = {
id: 1,
name: 'Alice',
email: 'alice@example.com',
createdAt: new Date()
};Intersection Types: &
Combine multiple types with the & operator. The result type has all properties of both. Useful for extending types.
type Timestamped = {
createdAt: Date;
updatedAt: Date;
};
type UserWithTimestamp = User & Timestamped;
// Has all User properties AND createdAt/updatedAtThe any Type — Escape Hatch
any opts out of type checking for a value. It's contagious — values derived from any are also any. Use as a last resort during migration; never as a long-term solution.
let data: any = fetch('/api/data'); // no type checking
data.foo.bar.baz; // no error — and no protection
// Better: use 'unknown' and narrow it:
let raw: unknown = getExternalData();
if (typeof raw === 'string') {
console.log(raw.toUpperCase()); // narrowed
}The unknown Type — Safe Alternative to any
unknown is the type-safe counterpart to any. You can't use an unknown value without first narrowing its type. It forces you to validate external data.
Tuples — Fixed-Length Arrays
A tuple is a fixed-length array where each position has a known type.
type Point = [number, number];
const origin: Point = [0, 0];
const p: Point = [3, 4];
// React useState returns a tuple:
const [count, setCount] = useState<number>(0);Quick Check
Which TypeScript feature lets a function accept either a string or a number?
Recap: Primitive Types Unions Aliases
Primitive types: string, number, boolean, null, undefined. Arrays: Type[]. Union types: A | B. Literal types for fixed value sets. type alias for reusable type names. Optional properties with ?. readonly for immutable properties. Prefer unknown over any for external data.
Frequently asked questions
Is the “Primitive Types Unions and Type Aliases” lesson free?
Yes — the full text of “Primitive Types Unions and Type Aliases” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “Primitive Types Unions and Type Aliases”?
Annotate variables with string, number, boolean, and arrays. Create union types with | and give them readable names with type aliases. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Primitive Types Unions and Type Aliases” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why TypeScript: Types Catch Bugs at Compile Time
- Primitive Types Unions and Type Aliases
- Interfaces and Object Types
- Compiling TS and tsconfig.json