Skip to content

Instantly share code, notes, and snippets.

@jbarnat
Created June 3, 2025 16:52
Show Gist options
  • Save jbarnat/b007f1a504b3b63aa336e2f4b5c4e563 to your computer and use it in GitHub Desktop.
Save jbarnat/b007f1a504b3b63aa336e2f4b5c4e563 to your computer and use it in GitHub Desktop.
assertExactKeys.ts
/**
* βœ… Use case:
* Validate that a list of string keys matches a TypeScript interface *exactly*:
* - No missing keys
* - No extra keys
*
* πŸ’‘ Great for:
* - DTO serialization (`toDBObject`)
* - Form field definitions
* - Schema-driven rendering
* - Backend API constraints
*
* β›” Catches bugs at compile-time β€” safe refactors guaranteed.
*
* Example below ensures `documentKeys` matches all keys of `IDocument` exactly.
*/
export function assertExactKeys<T>() {
return function <K extends readonly (keyof T)[]>(
keys: K &
(Exclude<keyof T, K[number]> extends never
? Exclude<K[number], keyof T> extends never
? unknown
: '❌ Extra keys in key list'
: '❌ Missing keys in key list')
) {
return keys;
};
}
// --- Example usage ---
export interface IDocument {
id: string;
name: string;
baseColor?: string;
baseColorHist?: string[];
createdAt: number;
updatedAt: number;
}
// βœ… Matches IDocument keys exactly β€” will error if one is missing or extra
export const documentKeys = assertExactKeys<IDocument>()([
'id',
'name',
'baseColor',
'baseColorHist',
'createdAt',
'updatedAt',
] as const);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment