TypeScript Generic

function sortByNameKey<T extends { name: string }>(arr: T[]): T[] {
    return arr.sort((a, b) => a.name.localeCompare(b.name));
}

// Example usage with objects having a 'name' property:
interface Person {
    name: string;
    age: number;
}

const people: Person[] = [
    { name: "Charlie", age: 20 },
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 }
];

const sortedPeople = sortByNameKey(people);
console.log(sortedPeople);
// Output:
// [
//     { name: "Alice", age: 25 },
//     { name: "Bob", age: 30 },
//     { name: "Charlie", age: 20 }
// ]

// Example usage with different objects having a 'name' property:
interface Product {
    name: string;
    price: number;
}

const products: Product[] = [
    { name: "Banana", price: 1.0 },
    { name: "Apple", price: 1.5 },
    { name: "Cherry", price: 2.0 }
];

const sortedProducts = sortByNameKey(products);
console.log(sortedProducts);
// Output:
// [
//     { name: "Apple", price: 1.5 },
//     { name: "Banana", price: 1.0 },
//     { name: "Cherry", price: 2.0 }
// ]

Leave a Comment