Using Typescript, I am trying to write a function that takes in a generic object and a key value mapping of validation rules to apply on each property. When using the keyof property to verify that keys passed in the "validators" object are in the TObject generic, I get An index signature parameter type must be either 'string' or 'number'. Later, when attempting to access a value in validators, I get No index signature with a parameter of type 'string' was found on type '{}'.
function isValid<TObject>(
o: TObject,
validators: {
[key: keyof TObject]: (o: TObject) => boolean;
}
) {
for (const validator in validators) {
if (!validators[validator](o)) {
return false;
}
}
return true;
}
type Todo = {
text: string;
details: string;
completed: boolean;
};
console.log(
isValid<Todo>(
{
text: "mow yard",
details: "needs to be completed asap",
completed: false
},
{
text: (o: Todo) => o.text.length > 0,
completed: (o: Todo) => !!o.completed
}
)
);