'How to ensure a list of property are present in a key list in TypeScript?
I have this code, which works as wanted. It takes an object, which is basically a list of properties (of any type). It should return an object with all same property key names, populated with 'true' (to be passed to prisma select query, but that is not important).
// properties of User to pick for UserForFriends type
const pickerUserForFriends = ["id", "avatarUrl", "firstname", "email"] as const;
// some kind of public profile
export type UserForFriends = Pick<User, typeof pickerUserForFriends[number]>;
// this type transform an object to another object with same keys, populated with 'true'
type PrismaSelector<T> = { [K in keyof T]: true };
// this method populate PrismaSelector<T> typed object, with 'true'
const instantiate = <T, K extends keyof T>(keys: Array<K>): PrismaSelector<T> => {
const obj: { [K in keyof T]?: true } = {};
for (const key of keys) obj[key] = true;
return obj as PrismaSelector<T>;
};
// used to select a friend, in a prisma query
export const selectUserForFriends: PrismaSelector<UserForFriends> = instantiate(Object.values(pickerUserForFriends));
That's work as awaited, but it does not guarantee at compile time that all keys of T will be filled in final object. At this time it does not really matter, because I am ensuring the list of properties before calling the instantiate function. BUT I want to know!
How can I set up the type of Keys parameter to ensure that all properties of T are present at the end?
Thank you for your help
Solution 1:[1]
This seems to work:
type HasAllKeys<T, Keys> =
keyof T extends never ? true :
Keys extends readonly [infer First, ...infer Rest]
? First extends keyof T
? HasAllKeys<Omit<T, First>, Rest>
: false : false;
It is just "looping" over all the keys in the array and checking if all of them are present.
You can use this in the return type of a function to validate the keys:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
