Sobes.tech
Middle

Porozprávajte o utilitárnych typoch v TypeScript.

sobes.tech AI

Odpoveď od AI

Využitie utilitárnych typov v TypeScript je spôsob, ako efektívne spravovať komplexné typy dát. Tieto vstavané typy umožňujú transformovať existujúce typy na nové, vykonávať rôzne užitočné operácie a zvyšovať flexibilitu a opakovateľnosť kódu. Medzi hlavné utilitárne typy patria:

  • Partial<Type>: Vytvára nový typ, kde všetky vlastnosti Type sú voliteľné.

    interface User {
      id: number;
      name: string;
      age: number;
    }
    
    type PartialUser = Partial<User>;
    // PartialUser bude { id?: number; name?: string; age?: number; }
    
  • Readonly<Type>: Vytvára nový typ, kde všetky vlastnosti Type sú iba na čítanie.

    interface Point {
      x: number;
      y: number;
    }
    
    type ReadonlyPoint = Readonly<Point>;
    // ReadonlyPoint bude { readonly x: number; readonly y: number; }
    
  • Pick<Type, Keys>: Vytvára typ výberom zadaných vlastností Keys z Type.

    interface Product {
      id: number;
      name: string;
      price: number;
      description: string;
    }
    
    type ProductSummary = Pick<Product, 'id' | 'name' | 'price'>;
    // ProductSummary bude { id: number; name: string; price: number; }
    
  • Omit<Type, Keys>: Vytvára typ vynechaním zadaných vlastností Keys z Type.

    interface Order {
      id: number;
      productId: number;
      quantity: number;
      timestamp: string;
    }
    
    type OrderDetails = Omit<Order, 'timestamp'>;
    // OrderDetails bude { id: number; productId: number; quantity: number; }
    
  • Exclude<Type, ExcludedUnion>: Vytvára typ vylúčením z Type tých prvkov, ktoré môžu byť priradené ExcludedUnion. Používa sa pre unie (union types).

    type Colors = 'red' | 'green' | 'blue' | 'yellow';
    type PrimaryColors = Exclude<Colors, 'yellow'>;
    // PrimaryColors bude 'red' | 'green' | 'blue'
    
  • Extract<Type, Union>: Vytvára typ výberom z Type tých prvkov, ktoré môžu byť priradené Union. Používa sa pre unie.

    type AllAnimals = 'dog' | 'cat' | 'fish' | 'bird';
    type PetAnimals = Extract<AllAnimals, 'dog' | 'cat'>;
    // PetAnimals bude 'dog' | 'cat'
    
  • NonNullable<Type>: Vytvára typ vylúčením hodnôt null a undefined z Type.

    type MaybeString = string | null | undefined;
    type NotNullableString = NonNullable<MaybeString>;
    // NotNullableString bude string
    
  • Record<Keys, Type>: Vytvára typ objektu, kde vlastnosti majú kľúče z Keys a hodnoty typu Type.

    type CityPopulation = Record<string, number>;
    // CityPopulation bude { [key: string]: number }
    
    const population: CityPopulation = {
      "Москва": 12635466,
      "Санкт-Петербург": 5381033,
    };
    
  • Parameters<Type>: Vráti tuple (pole) typov parametrov funkcie Type.

    function greet(name: string, age: number): string {
      return `Hello, ${name}! You are ${age}.`;
    }
    
    type GreetParams = Parameters<typeof greet>;
    // GreetParams bude [name: string, age: number]
    
  • ReturnType<Type>: Vráti typ návratovej hodnoty funkcie Type.

    function calculateSum(a: number, b: number): number {
      return a + b;
    }
    
    type SumResult = ReturnType<typeof calculateSum>;
    // SumResult bude number
    
  • ConstructorParameters<Type>: Vráti tuple alebo pole typov parametrov konštruktora triedy Type.

    class MyClass {
      constructor(name: string, id: number) {}
    }
    
    type MyClassParams = ConstructorParameters<typeof MyClass>;
    // MyClassParams bude [name: string, id: number]
    
  • InstanceType<Type>: Vráti typ inštancie triedy Type.

    class AnotherClass {
      value: string;
      constructor(v: string) {
        this.value = v;
      }
    }
    
    type AnotherClassInstance = InstanceType<typeof AnotherClass>;
    // AnotherClassInstance bude AnotherClass
    

Použitie utilitárnych typov robí kód bezpečnejším, ľahko udržiavateľným a výstižnejším, čo umožňuje efektívne riadiť zložité typy dát.