Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Created March 11, 2024 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaffei/f85c91befd407ffd642be5cc95b740d1 to your computer and use it in GitHub Desktop.
Save joemaffei/f85c91befd407ffd642be5cc95b740d1 to your computer and use it in GitHub Desktop.
Type-safe key mirror
function keyMirror<Obj>(...args: (keyof Obj)[]): Readonly<{ [Key in keyof Obj]: Key }> {
let obj = {};
for (let arg of args) {
Object.defineProperty(obj, arg, {
configurable: false,
enumerable: true,
value: arg,
writable: false,
});
}
return obj as Readonly<{ [Key in keyof Obj]: Key }>;
}
@joemaffei
Copy link
Author

Example:

const stopLight = keyMirror('red', 'yellow', 'green');

stopLight.red === 'red' // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment