Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created February 7, 2025 14:36
Show Gist options
  • Save Kcko/070ee7d9f23bb4d368002267c84c086b to your computer and use it in GitHub Desktop.
Save Kcko/070ee7d9f23bb4d368002267c84c086b to your computer and use it in GitHub Desktop.
/*
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
// 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
// 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
// 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment