Skip to content

Instantly share code, notes, and snippets.

@alii
Created August 25, 2021 14:12
Show Gist options
  • Save alii/e90914d10c15245f12a3e71ec74768de to your computer and use it in GitHub Desktop.
Save alii/e90914d10c15245f12a3e71ec74768de to your computer and use it in GitHub Desktop.
Infer object values while strictly specifying keys in TypeScript
/**
* TypeScript currently lacks a way of typing a record of keys only but not values.
* we need this because we want an object of typed keys but we want to leave the values inferred.
* thankfully, we can do this with generics. This function allows the second generic's values to be inferred
* so that our object is fully type safe for hugely complex types, but we can guarantee that all the keys we need exist.
* It's not perfect, but it gets the job done for the time being
*/
export function ensureKeys<T>() {
/**
* Function that returns the value that gets put in, values are type-safely inferred
*/
return function <X extends Record<keyof T, unknown>>(data: X) {
return data;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment