I wan't to create a generic function for validating objects. I want it to accept an options object of the following signature:
export interface ValidationOptions<T, K extends keyof T = keyof T> {
validators: Map<K, (value: T[K]) => string | null>
}
I want to be able to map from K to an array of validator functions that would accept an argument of type T[K]. The issue i have is that T[K] will resolve to each possible value in T, and not the specific value for the given key.
The code below should hopefully clarify what i mean.
export interface ValidationOptions<T, K extends keyof T = keyof T> {
validators: Map<K, (value: T[K]) => string | null>
}
function fooValidator(value: string) {
if (value === "foo") {
return "Value can't be foo"
}
return null;
}
function isNotTrueValidator(value: boolean) {
if (!value) {
return "Value must be true"
}
return null;
}
interface ObjectToValidate {
stringy: string;
booly: boolean;
}
//(value: T[K]) => string | null will resolve to value: string | boolean here
//Can i make it resolve to the type for the given property instead?
const options: ValidationOptions<ObjectToValidate> = {
//This results in an error with strictFunctionTypes enabled
validators: new Map([
//How can i
["stringy", fooValidator]
])
}