我有这样的功能:
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 });
因此,它是种相反的操作,例如:
flatAttributes{ id: string, attributes: { key: number } }) === { id: string, key: number }
我们的观点:汇编createRelationship
thorws:
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
。
任何想法如何声明没有不安全的映射这个功能呢? 为什么打字稿这样的表现?
操场