๐—–๐—ผ๐—บ๐—ฏ๐—ถ๐—ป๐—ถ๐—ป๐—ด ๐—ง๐˜†๐—ฝ๐—ฒ๐˜€ ๐—ถ๐—ป ๐—ง๐˜†๐—ฝ๐—ฒ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜

TypeScript lets you combine types to create flexible code. You can build better structures using these four methods.

  1. Union Types (|) A value acts as one of several types. This is useful when a variable accepts different formats.

Example: type ID = string | number;

  1. Intersection Types (&) This merges multiple types into one. The final value must meet every requirement from all combined types. It works well for composition.

Example: type Person = { name: string; cpf: string }; type Company = { cnpj: string; reason: string };

type LegalEntity = Person & Company;

  1. Type Aliases You create a reusable name for a type. This keeps your code clean.

Example: type Name = string; type Age = number;

  1. Keyof Operator The keyof operator pulls the keys from a type. It creates a union of those keys as strings.

Example: type Invoice = { number: string; value: number; date: Date; };

type InvoiceFields = keyof Invoice; // This equals "number" | "value" | "date"

Why use keyof? Without it, you use loose strings. This leads to errors. With keyof, TypeScript checks your keys. If you try to access a key that does not exist, you get a compiler error immediately.

Use keyof to build type-safe functions that access object properties.

Source: https://dev.to/yuripeixinho/typescript-combinando-tipos-combining-types-5d8j