Паттерн TypeScript для чистой и типобезопасной выборки данных
type KeyOf<T> = Extract<keyof T, string>;
const mapData = <T extends object, K extends KeyOf<T>>(
data: readonly T[],
key: K,
) => data.map((item) => item[key]);
const categories = [
{ id: 1, name: "Clothing" },
{ id: 2, name: "Footwear" },
] as const;
const variants = [
{ id: 1, name: "Red - Large" },
{ id: 2, name: "Blue - Medium" },
] as const;
const sizes = [
{ id: 1, label: "Small" },
{ id: 2, label: "Medium" },
] as const;
// Типобезопасно, неизменно и полностью выводится по типам
console.log(mapData(categories, "name")); // ["Clothing", "Footwear"]
console.log(mapData(variants, "name")); // ["Red - Large", "Blue - Medium"]
console.log(mapData(sizes, "label")); // ["Small", "Medium"]
@WebDev_Plus
