This question starts off from the answer to this question:
https://stackoverflow.com/a/60807986/13809150
Is there a way to make an array of SingleKey with all different keys? Doing Array<SingleKey<T>>
OR SingleKey<T>[]
makes it so they all need the same key. (e.g. [{key1: "value1"},{key2:"value1"}]
throws and error because key1!==key2. Which is sadly the exact opposite behavior that I am looking for.
This is what I am trying to do/have done:
// From https://stackoverflow.com/a/50375286
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
// From: https://stackoverflow.com/a/53955431
type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
type SingleKey<T> = IsUnion<keyof T> extends true ? never : {} extends T ? never : T;
function f<T extends Record<string, any>>(obj: SingleKey<T>[]) {
// console.log({ obj });
}
f([{}]); // errors here! This is correct
f([{ x: 5 }, { x: 5 }]); // Should have error because same key (NEED TO FIX)
f([{ x: 5 }, { y: 6 }]); // Should not have error because of opposite keys (NEED TO FIX)
f([{ x: 5}, { y : 6 }, { y : 4}]) // Should fail because duplicate key
The above code in a ts playground