๐๐ผ๐บ๐ฏ๐ถ๐ป๐ถ๐ป๐ด ๐ง๐๐ฝ๐ฒ๐ ๐ถ๐ป ๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐
TypeScript lets you combine types to create flexible code. You can build better structures using these four methods.
- Union Types (|) A value acts as one of several types. This is useful when a variable accepts different formats.
Example: type ID = string | number;
- 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;
- Type Aliases You create a reusable name for a type. This keeps your code clean.
Example: type Name = string; type Age = number;
- 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