简体   繁体   中英

Typescript An index signature parameter type must be either 'string' or 'number' when using keyof

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM