/ Gists / Generic constraint
On gists

Generic constraint

Typescript

index.ts Raw #

/*
omezení, která můžeme přidat na generické typy, aby splňovaly určité podmínky.
*/

// T musí být objekt
function getProperty<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

// Použití:
const person = { name: "Jan", age: 30 };
const name = getProperty(person, "name"); // OK
const invalid = getProperty(person, "invalid"); // Chyba - 'invalid' není klíč v person

index2.ts Raw #

// T musí mít vlastnost 'length'
function printLength<T extends { length: number }>(item: T): void {
    console.log(item.length);
}

// Použití:
printLength("hello");     // OK - string má length
printLength([1, 2, 3]);   // OK - pole má length
printLength({ length: 5 }); // OK - objekt má vlastnost length
printLength(123);         // Chyba - číslo nemá length

index3.ts Raw #

// T musí mít metodu getId, která vrací string
interface HasId {
    getId(): string;
}

function processItem<T extends HasId>(item: T): void {
    console.log(item.getId());
}

// Použití:
class User implements HasId {
    getId() { return "user-123"; }
}

processItem(new User()); // OK
processItem({ getId: () => "test" }); // OK
processItem({ name: "Jan" }); // Chyba - chybí metoda getId

index4.ts Raw #

// T může být jen string nebo number
type StringOrNumber = string | number;

function logValue<T extends StringOrNumber>(value: T): void {
    console.log(value);
}

logValue("hello"); // OK
logValue(123);     // OK
logValue(true);    // Chyba - boolean není povolen

index5.ts Raw #

function compare<T extends number | string>(a: T, b: T): boolean {
  return a > b;
}

console.log(compare(10, 5)); // true
console.log(compare("apple", "banana")); // false

// Nesprávné použití - typ boolean neodpovídá omezení
// console.log(compare(true, false)); // Chyba: Type 'boolean' is not assignable