I have created a function that does the runtime requirement of checking for null and undefined not being true:
function hasFields<T>(obj: T | T[], ...fields: (keyof T)[]): boolean {
const inObj: { (obj: T): boolean } = (obj) => fields.every((f) => obj[f] != null);
if (Array.isArray(obj)) {
return obj.every((o) => inObj(o));
} else {
return inObj(obj);
}
}
But what I would really like is something that would either return an obj with an updated type, or being able to use this in an if statement and be able to get the types updated within the context of the if statement.
I have seen questions like this: Typescript type RequireSome<T, K extends keyof T> removing undefined AND null from properties but it doesn't do it for a list of fields.
If it helps, the fields are known at compile time.