2

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
    }
  )
);

1 Answer 1

3

You should use the keyword in instead of :, as : is for index type (string, number, symbol)

function isValid<TObject>(
  o: TObject,
  validators: {
    [key in keyof TObject]: (o: TObject) => boolean;
  }
) {
  for (const validator in validators) {
    if (!validators[validator](o)) {
      return false;
    }
  }

  return true;
}

if a key is optional, use ?:

  validators: {
    [key in keyof TObject]?: (o: TObject) => boolean;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.