I'm looking to develop a generic type validation function that checks the type of an object's property. However, I'd prefer not to have to specify both the field as an argument value and a type value.
While the following code functions correctly, it seems somewhat repetitive:
function isFieldPopulated<T1, T2, K extends keyof T1>(doc: T1, field: K): doc is Omit<T1, K> & Record<K, T2> {
// check if T1[K] is a T2
return ...;
}
if (isFieldPopulated<Post, Category, 'category'>(data, 'category')) {
// data.category is a Category type
}
My goal is to eliminate the need to define 'category' here
<Post, Category, 'category'>
AND here (data, 'category')
. Is there a way for TypeScript to recognize that the field
argument extends keyof T1 without having to include 'category' in <..., 'category'>
since it's already provided as a string argument?
UPDATE: Check out this minimal working example.