Created
June 3, 2025 16:52
-
-
Save jbarnat/b007f1a504b3b63aa336e2f4b5c4e563 to your computer and use it in GitHub Desktop.
assertExactKeys.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* β 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