-
Notifications
You must be signed in to change notification settings - Fork 201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Provide more utility functions (pick, ...) #24
Comments
A export const omit = <Obj, Keys extends keyof Obj>(obj: Obj, keys: Keys[]): Omit<Obj, Keys> => {
return keys.reduce((acc, key) => {
const { [key]: omit, ...rest } = acc;
return rest;
}, obj as any)
}
// Maybe this is better because it creates a new object just once
export const omit2 = <Obj, Keys extends keyof Obj>(obj: Obj, keys: Keys[]): Omit<Obj, Keys> => {
const result = Object.assign({}, obj);
keys.forEach((key) => {
delete result[key];
});
return result;
} Maybe deeply picking and omiting by specifing a schema. dpick(obj, {
key: true, // Picks all keys from nested object 'key'
key2: ["key"], // Picks only 'key' field from nested object 'key2'
key3: { // Picks all from 'key' nested object but only field 'key' of 'key2' object from object 'key3'
key: true,
key2: ["key"]
}
}); |
It would be great if pick(doc, [
'slug',
'date',
'title',
'description',
'featuredImage', // non-required field
])
) |
@pmarsceill that's a great suggestion that's often needed with Next.js type ConvertUndefined<T> = OrNull<{
[K in keyof T as undefined extends T[K] ? K : never]-?: T[K];
}>;
type OrNull<T> = { [K in keyof T]: Exclude<T[K], undefined> | null };
type PickRequired<T> = {
[K in keyof T as undefined extends T[K] ? never : K]: T[K];
};
type ConvertPick<T> = ConvertUndefined<T> & PickRequired<T>;
export const pick = <Obj, Keys extends keyof Obj>(
obj: Obj,
keys: Keys[]
): ConvertPick<{ [K in Keys]: Obj[K] }> => {
return keys.reduce((acc, key) => {
acc[key] = obj[key] ?? null;
return acc;
}, {} as any);
}; |
There's a number of common utility functions which are useful in Contentlayer projects (e.g. a type-safe
pick
function) like below or here:We should provide these utility functions out of the box with Contentlayer. Candidates:
pick
: Type-safe function similar to TSPick
typefindById
If you'd like to see an other utility function added, please share your requests/ideas in the comments below. 🙏
The text was updated successfully, but these errors were encountered: