KP
KP
TTCTheo's Typesafe Cult
Created by KP on 1/7/2023 in #questions
Types for deep merging defaults in TS
export const deepMergeDefaults = <T>(
defaultObj: {
[k: string]: unknown;
},
passedObj: { [k: string]: unknown }
) => {
let result: typeof defaultObj = {};

for (let [key, value] of Object.entries(defaultObj)) {
if (!passedObj[key as keyof typeof passedObj]) {
result[key] = value;
continue;
}

if (typeof value === "object" && !Array.isArray(value) && value) {
result[key] = deepMergeDefaults(
value as typeof defaultObj,
passedObj[key as keyof typeof passedObj] as typeof defaultObj
);
continue;
}

result[key] = passedObj[key];
}

return result as T;
};
export const deepMergeDefaults = <T>(
defaultObj: {
[k: string]: unknown;
},
passedObj: { [k: string]: unknown }
) => {
let result: typeof defaultObj = {};

for (let [key, value] of Object.entries(defaultObj)) {
if (!passedObj[key as keyof typeof passedObj]) {
result[key] = value;
continue;
}

if (typeof value === "object" && !Array.isArray(value) && value) {
result[key] = deepMergeDefaults(
value as typeof defaultObj,
passedObj[key as keyof typeof passedObj] as typeof defaultObj
);
continue;
}

result[key] = passedObj[key];
}

return result as T;
};
Similar to lodash's merge defaults, the above function deep merges optional fields by using a default object. What I want is to be able to input an object with type
type ContainerCustom = {
position?: {
left?: keyof typeof CONTAINER_PROPS["position"]["left"];
top?: keyof typeof CONTAINER_PROPS["position"]["top"];
};
padding?: typeof CONTAINER_PROPS["padding"];
};
type ContainerCustom = {
position?: {
left?: keyof typeof CONTAINER_PROPS["position"]["left"];
top?: keyof typeof CONTAINER_PROPS["position"]["top"];
};
padding?: typeof CONTAINER_PROPS["padding"];
};
and get back an object with type
type ContainerCustom = {
position: {
left: keyof typeof CONTAINER_PROPS["position"]["left"];
top: keyof typeof CONTAINER_PROPS["position"]["top"];
};
padding: typeof CONTAINER_PROPS["padding"];
};
type ContainerCustom = {
position: {
left: keyof typeof CONTAINER_PROPS["position"]["left"];
top: keyof typeof CONTAINER_PROPS["position"]["top"];
};
padding: typeof CONTAINER_PROPS["padding"];
};
1 replies
TTCTheo's Typesafe Cult
Created by KP on 1/5/2023 in #questions
Typescript doesn't show which prop should be provided
3 replies
TTCTheo's Typesafe Cult
Created by KP on 1/2/2023 in #questions
Correct way to tell typescript object's index is not undefined when mapping over keys ?
4 replies