Type Composition

Loading concept...

๐Ÿงฉ TypeScript Type Composition: Building with LEGO Blocks

Imagine you have a box of LEGO blocks. Each block has a shape and color. Now, what if you could combine blocks in special ways to build amazing things? Thatโ€™s exactly what Type Composition is in TypeScript!


๐ŸŽฏ The Big Idea

Think of types like ingredients in a kitchen. Sometimes you need just one ingredient (a simple type). But often, you want to mix ingredients together to make something new and delicious!

TypeScript gives you special tools to combine types:

  • Mix them together (Union)
  • Stack them on top of each other (Intersection)
  • Lock them so nobody changes them (readonly/const)

Letโ€™s explore each one!


๐Ÿ”€ Union Types: โ€œThis OR Thatโ€

What is it?

A union type says: โ€œThis can be one thing OR another thing.โ€

Think of a traffic light. It can be:

  • ๐Ÿ”ด Red
  • ๐ŸŸก Yellow
  • ๐ŸŸข Green

But it can ONLY be ONE color at a time!

Example

type TrafficLight = "red" | "yellow" | "green";

let light: TrafficLight = "red";    // โœ… OK
light = "green";                     // โœ… OK
light = "purple";                    // โŒ Error!

Real Life Use

type Pet = "cat" | "dog" | "fish";
type Age = number | string;

let myPet: Pet = "cat";       // โœ…
let myAge: Age = 10;          // โœ… number works
myAge = "ten years old";      // โœ… string works too!

๐ŸŽจ Visual Flow

graph TD A[Union Type] --> B[Option 1] A --> C[Option 2] A --> D[Option 3] B --> E[Pick ONE!] C --> E D --> E

Remember: Union = Choose ONE from many options!


โž• Intersection Types: โ€œThis AND Thatโ€

What is it?

An intersection type says: โ€œThis must be everything combined!โ€

Imagine a superhero who has:

  • Flying powers (like Superman)
  • Spider powers (like Spider-Man)

With intersection, your hero gets BOTH powers at once!

Example

type CanFly = {
  fly: () => void;
};

type CanSwim = {
  swim: () => void;
};

type SuperHero = CanFly & CanSwim;

const aquaFlyer: SuperHero = {
  fly: () => console.log("Whoosh!"),
  swim: () => console.log("Splash!")
};

๐ŸŽจ Visual Flow

graph TD A[Type A] --> C[Intersection A & B] B[Type B] --> C C --> D[Has ALL properties!]

Remember: Intersection = Get EVERYTHING from all types!


๐Ÿ“ Literal Types: Exact Values Only

What is it?

A literal type is super strict. It says: โ€œOnly THIS exact value is allowed!โ€

Itโ€™s like a password. Not just any wordโ€”only the EXACT word works.

Example

type Yes = "yes";
type Five = 5;
type IsTrue = true;

let answer: Yes = "yes";    // โœ… Only "yes" works
answer = "Yes";             // โŒ Error! Capital Y!
answer = "yeah";            // โŒ Error! Not exact!

let count: Five = 5;        // โœ… Only number 5
count = 6;                  // โŒ Error!

Combining Literals

type Direction = "up" | "down" | "left" | "right";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

let move: Direction = "up";     // โœ…
let roll: DiceRoll = 4;         // โœ…
roll = 7;                       // โŒ Error!

๐Ÿ”ค Template Literal Types: Smart Text Building

What is it?

Template literals let you build new text types from pieces!

Itโ€™s like Mad Libsโ€”you fill in the blanks to create new sentences.

Example

type Color = "red" | "blue" | "green";
type Size = "small" | "large";

type TShirt = `${Size}-${Color}`;
// Creates: "small-red" | "small-blue" |
//          "small-green" | "large-red" |
//          "large-blue" | "large-green"

let myShirt: TShirt = "small-red";   // โœ…
myShirt = "medium-red";               // โŒ Error!

๐ŸŽจ Visual Flow

graph TD A[Size: small, large] --> C[Template] B[Color: red, blue, green] --> C C --> D["small-red"] C --> E["small-blue"] C --> F["large-red"] C --> G["...and more!"]

๐Ÿ”’ readonly vs const: Locking Things Down

Whatโ€™s the difference?

Think of a museum:

  • const = The display case is bolted to the floor (canโ€™t move it)
  • readonly = The items INSIDE the case canโ€™t be touched

const Example

const myName = "Alex";
myName = "Bob";  // โŒ Error! Can't change!

const myPets = ["cat", "dog"];
myPets.push("fish");  // โœ… Array content CAN change!
myPets = [];          // โŒ Can't reassign!

readonly Example

type Person = {
  readonly name: string;
  age: number;
};

const me: Person = { name: "Alex", age: 10 };
me.age = 11;      // โœ… age can change
me.name = "Bob";  // โŒ Error! name is readonly!

Quick Comparison

Feature const readonly
What it locks The variable itself Property inside object
Can reassign? โŒ No โŒ No (that property)
Array push? โœ… Yes โŒ No (if readonly array)

๐Ÿ“ฆ Destructuring with Types

What is it?

Destructuring is like unpacking a gift box. You take things OUT and give them names!

Object Destructuring

type Gift = {
  toy: string;
  color: string;
  price: number;
};

const present: Gift = {
  toy: "robot",
  color: "blue",
  price: 20
};

// Unpack the gift!
const { toy, color }: Gift = present;
console.log(toy);    // "robot"
console.log(color);  // "blue"

Array Destructuring

const scores: [number, number, number] = [95, 87, 92];

const [first, second, third] = scores;
console.log(first);  // 95

With Default Values

type Settings = {
  theme?: string;
  volume?: number;
};

const config: Settings = { theme: "dark" };

const {
  theme = "light",
  volume = 50
}: Settings = config;

console.log(theme);   // "dark" (from config)
console.log(volume);  // 50 (default used!)

๐Ÿค” Object vs object vs {}

This is tricky! Letโ€™s make it simple:

The Three Types

Type What it means Example
Object Almost anything (avoid!) String, Number, Array, {}
object Only non-primitives {}, [], function
{} Any non-null/undefined Almost everything!

Visual Guide

graph TD A["{} - Widest"] --> B["object - Middle"] B --> C["Specific type - Best!"] D["Object - Avoid!"] -.-> A

Examples

// Object (capital O) - TOO broad, avoid!
let a: Object = "hello";     // โœ… string works
let b: Object = 42;          // โœ… number works
let c: Object = {};          // โœ… object works

// object (lowercase) - non-primitives only
let d: object = {};          // โœ… object literal
let e: object = [];          // โœ… array is object
let f: object = "hello";     // โŒ Error! string!

// {} - almost anything except null/undefined
let g: {} = "hello";         // โœ… works
let h: {} = 42;              // โœ… works
let i: {} = null;            // โŒ Error!

๐ŸŒŸ Best Practice

// โŒ Avoid these - too vague
let bad1: Object = {};
let bad2: object = {};
let bad3: {} = {};

// โœ… Use specific types!
type User = {
  name: string;
  age: number;
};

let good: User = { name: "Alex", age: 10 };

๐ŸŽ‰ Putting It All Together

Hereโ€™s a real example using EVERYTHING we learned:

// Literal types for status
type Status = "active" | "inactive" | "pending";

// Template literal for IDs
type UserId = `user-${number}`;

// Types to combine
type HasName = { readonly name: string };
type HasEmail = { email: string };

// Intersection: combine both!
type User = HasName & HasEmail & {
  id: UserId;
  status: Status;
};

// Create a user
const user: User = {
  id: "user-123",
  name: "Alex",
  email: "alex@example.com",
  status: "active"
};

// Destructure with types
const { name, status }: User = user;

user.name = "Bob";    // โŒ readonly!
user.status = "inactive"; // โœ… OK

๐Ÿง  Key Takeaways

  1. Union (|) = Pick ONE from options
  2. Intersection (&) = Combine ALL properties
  3. Literal = Exact value only
  4. Template Literal = Build text types from pieces
  5. readonly = Lock a property
  6. const = Lock the whole variable
  7. Destructuring = Unpack with types
  8. Use specific types over Object/object/{}

Youโ€™re now a Type Composition master! ๐Ÿ† These building blocks let you create any type you can imagine!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.