I've created a utility function called UniqueForProp
that takes an array of objects and a specified property within the object. It then generates a union type containing all possible values for that property across the array:
type Get<T, K> = K extends `${infer FK}.${infer L}`
? FK extends keyof T
? Get<T[FK], L>
: never
: K extends keyof T
? T[K]
: never;
type UniqueForProp<T extends readonly Record<string, any>[], P extends string> = {
[K in keyof T]: Readonly<Get<T[K], P>>;
}[keyof T];
For example, using the test case below should result in the union type 123 | 456
:
const data = [
{ id: 123, color: "blue" },
{ id: 456, color: "red" },
] as const;
type Data = typeof data;
type U = UniqueForProp<Data, "id">;
However, the current implementation produces additional unwanted values along with 123
and 456
:
https://i.sstatic.net/4s4wE.png
If anyone can assist me in refining this code, it would be greatly appreciated.