The function useHider
was created to conceal specific values from an object with the correct type. For example, using
const res = useHider({ id: 1, title: "hi"}, "id")
, will result in { title: "hi" }
being returned. Attempting to access res.id
will trigger a TypeScript error.
Additionally, the hideQueryResult
function allows for default hiding of createdAt
, updatedAt
, and deletedAt
values, or the option to specify additional parameters to hide more values from an object.
const useHider = <T, K extends keyof T>(obj: T, keysToHide: K[]) => {
let res = obj;
keysToHide.forEach((key) => {
delete res[key];
});
return res as Omit<T, K>;
};
const hideQueryResult = <T, K extends keyof T>(
query: T,
keysToHide: K[] = [],
) => {
const at = ["createdAt", "updatedAt", "deletedAt"] as K[];
const allKeysToHide = [...keysToHide, ...at];
const res = useHider(query, allKeysToHide);
return res;
};
However, when attempting to utilize hideQueryResult
to hide certain values, the desired outcome is not achieved.
const source = {
id: "01ABC",
title: "123",
createdAt: "ABC",
updatedAt: "ABC",
deletedAt: "ABC",
};
const res1 = useHider(source, ["createdAt", "updatedAt", "deletedAt"]);
console.log(res1.id); // success (expected)
console.log(res1.createdAt); // failed (expected)
const res2 = hideQueryResult(source);
console.log(res2.id); // failed (not expected)
const res3 = hideQueryResult(source, ["id"]);
console.log(res3.createdAt); // success (not expected)
What steps can be taken to ensure it functions correctly?