My goal is to create a TypeScript type generic that has the following structure:
type APIDataShape<T extends { id: unknown } | Array<{ id: unknown }>> =
T extends Array<any>
? Array<{
id: T[number]["id"];
attributes: Omit<T, "id">;
}>
: {
id: T["id"];
attributes: Omit<T, "id">;
};
The concept behind it is simple: I am looking for an object or an array of objects with an 'id' property, and I want to transform it into a different shape.
However, as I write the code above, I encounter an error on the id: T["id"];
line, which says:
Type '"id"' cannot be used to index type 'T'
This error perplexes me because it should be evident that if T isn't an array, then it must be an object with {id: unknown}. So why does TypeScript claim that it cannot be indexed?
I have tried various approaches to resolve this issue without success. If anyone can shed light on why this error is occurring, I would greatly appreciate it.
(P.S. I understand that using two extend
clauses could potentially fix the problem, but I am particularly interested in understanding the underlying reason behind it. It seems to me that even with just one extend
, it should work as intended. Hence, I seek clarity on why it failed.)
Thank you.