У меня есть такая функция:
const createRelationship = <T extends { id: string }>(
includedItems: Array<DataResponse<T>>,
categories: Array<{ id: string, type: string }>,
): Array<T> => {
return categories.map(({ id }) =>
includedItems.find((includedItem) => includedItem.id === id) as DataResponse<T>)
.map(flatAttributes);
};
Требуется универсальный тип T. Первым аргументом является массив DataResponse, где:
interface DataResponse<T extends { id: string }, R = void> {
id: string;
attributes: Omit<T, 'id'>;
}
и
type Omit<A extends object, K extends keyof A> = Pick<A, Exclude<keyof A, K>>;
так
type Example = DataResponse<{ id: string, key: number }> // { id: string, attributes: { key: number } };
Функция flatAttributes
выглядит так:
const flatAttributes = <T extends { id: string, attributes: any }>(item: T): { id: string } & T['attributes'] =>
({...item.attributes, ...item });
Так что это своего рода обратная операция, например ::1017*
flatAttributes{ id: string, attributes: { key: number } }) === { id: string, key: number }
Теперь к делу: Компиляция createRelationship
Шипов:
Type '({ id: string; } & Pick<T, Exclude<keyof T, "id">>)[]' is not assignable to type 'T[]'.
Type '{ id: string; } & Pick<T, Exclude<keyof T, "id">>' is not assignable to type 'T'.
Где Pick<T, Exclude<keyof T, "id">>'
равно Omit<T, 'key'>
и Omit<T, 'key'> & {key: string}
должно быть одинаковым T
.
Есть идеи, как объявить эту функцию без небезопасного отображения? И почему TypeScript так себя ведет?
Детская площадка