A
arktype•3w ago
san

Is there a way to "deep" require a type?

I have a type with a lot of deeply nested types and a lot of keys in them are optional. I then want to make the same type but with all keys required i.e remove the optional. Is there an easy way to do this? I know you can use .require() but that only works on the top level keys, not the nested ones
3 Replies
san
sanOP•3w ago
OH i can use scopes what a godsend
ssalbdivad
ssalbdivad•3w ago
There's an example of how to create a deepPartial generic here you could adapt: https://discord.com/channels/957797212103016458/957804102685982740/1348929382261067777
san
sanOP•2w ago
incredible, thank you! tried this solution but seems like it doesnt apply to the elements in arrays? how do I fix that im just gonna use scopes I think this is a bug okay scopes is annoying to use for this usecase 💔 I somehow came up with this monstrosity which seems to work (and I barely understand how lol):
function deepRequired<o extends type<object>>(
o: o
): type<RecursiveRequired<o["t"]>>;
function deepRequired(o: type<Record<string, unknown> | unknown[]>): unknown {
if (o.extends("Array")) {
return o
.select({
kind: "sequence",
method: "assertFind",
boundary: "shallow",
})
.variadic?.map((prop) =>
prop.value.extends("object")
? ({
...prop,
kind: "required",
value: deepRequired(prop.value as never),
} as never)
: { ...prop, kind: "required" }
)
.array();
}
return o.map((prop) =>
prop.value.extends("object")
? {
...prop,
kind: "required",
value: deepRequired(prop.value as never),
}
: { ...prop, kind: "required" }
);
}
function deepRequired<o extends type<object>>(
o: o
): type<RecursiveRequired<o["t"]>>;
function deepRequired(o: type<Record<string, unknown> | unknown[]>): unknown {
if (o.extends("Array")) {
return o
.select({
kind: "sequence",
method: "assertFind",
boundary: "shallow",
})
.variadic?.map((prop) =>
prop.value.extends("object")
? ({
...prop,
kind: "required",
value: deepRequired(prop.value as never),
} as never)
: { ...prop, kind: "required" }
)
.array();
}
return o.map((prop) =>
prop.value.extends("object")
? {
...prop,
kind: "required",
value: deepRequired(prop.value as never),
}
: { ...prop, kind: "required" }
);
}

Did you find this page helpful?