Is it possible for TypeScript to define an array that enforces a unique key constraint for specified objects?
Check out this demo showing the constraints.
type Magician = {
distinctKey: string;
lastName: string;
};
// How, if at all, can we make line 19 be a compiler error?
type ObjectArrayWithDistinctKey<TItem, TKey> = TItem[];
const example: ObjectArrayWithDistinctKey<Magician, 'distinctKey'> = [
{
distinctKey: 'ammar1956',
lastName: 'Ammar'
},
{
distinctKey: 'vernon1894',
lastName: 'Vernon'
},
{
distinctKey: 'ammar1956', // error!
lastName: 'Ammar'
}
];
Perhaps using a Map instead of an array would be more suitable for this scenario.