@fendrarog
Учу программирование.

Argument of type 'string' is not assignable to parameter of type '"contacts.github" | «contacts.vk» | ... 5 more ... | "contacts.mainLink"'.ts(2345)?

В этом коде я использую библиотеку react-hook-form.
В data у меня типизация :
(parameter) data: {
    aboutMe?: string;
    userId: number;
    lookingForAJob: boolean;
    lookingForAJobDescription: string;
    fullName: string;
    contacts: {
        github: string;
        vk: string;
        facebook: string;
        instagram: string;
        twitter: string;
        website: string;
        youtube: string;
        mainLink: string;
    };
    photos: {
        ...;
    };
}

Вот data:
const { register, handleSubmit } = useForm<ProfileType>({
    defaultValues: { ...profile },
  });

  const onSubmit: SubmitHandler<ProfileType> = async (data) => {
    await dispatch(updateOwnersProfile(data));
    jumpToNonEditMode();
  };


Я мапплю ключи объекта contacts и инпутам задаю имена через {...register("contacts." + key)}
{Object.keys(profile.contacts).map((key) => {
            return (
              <div key={key} className={s.contact}>
                <b>{key} :</b>
                <input {...register("contacts." + key)} placeholder={key} />
              </div>
            );
          })}

но получаю тайпскрипт ошибку:
TS2345: Argument of type 'string' is not assignable to parameter of type '"aboutMe" | "userId" | "lookingForAJob" | "lookingForAJobDescription" | "fullName" | "contacts" | "photos" | "contacts.github" | "contacts.vk" | "contacts.facebook" | "contacts.instagram" | ... 5 more ... | "photos.large"'.
    60 |               <div key={key} className={s.contact}>
    61 |                 <b>{key} :</b>
  > 62 |                 <input {...register("contacts." + key)} placeholder={key} />
       |                                     ^^^^^^^^^^^^^^^^^
    63 |               </div>
    64 |             );
    65 |           })}

В итоге получается что имена инпутов ("contacts." + key) имеют тип string, а тайпскрипт ожидает "contacts.github" | "contacts.vk" | "contacts.facebook" | "contacts.instagram" | ... 5 more.

Подскажите пожалуйста как пофиксить типизацию. Код при этом работает.
Полный код:
const ProfileDataForm: React.FC<PropsType> = ({
  profile,
  isOwner,
  jumpToNonEditMode,
}) => {
  const dispatch = useDispatch();

  const { register, handleSubmit } = useForm<ProfileType>({
    defaultValues: { ...profile },
  });

  const onSubmit: SubmitHandler<ProfileType> = async (data) => {
    await dispatch(updateOwnersProfile(data));
    jumpToNonEditMode();
  };

  return (
    <div className={s.descriptionBlock}>
      <div className={s.descriptionItem}>
        <ProfilePhotoData photos={profile.photos} isOwner={isOwner} />
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className={s.descriptionItem}>
          <input {...register("fullName")} placeholder="Full name" />
        </div>
        <div className={s.descriptionItem}>
          <b>About me: </b>
          <input {...register("aboutMe")} placeholder="About me" />
        </div>
        <div className={s.descriptionItem}>
          <b>Looking for a job: </b>
          <input type="checkbox" {...register("lookingForAJob")} />
        </div>
        <div className={s.descriptionItem}>
          <b>My professional experience: </b>
          <input
            {...register("lookingForAJobDescription")}
            placeholder="My professional experience"
          />
        </div>
        <div className={s.descriptionItem}>
          <b>Contacts: </b>
          {Object.keys(profile.contacts).map((key) => {
            return (
              <div key={key} className={s.contact}>
                <b>{key} :</b>
                <input {...register("contacts." + key)} placeholder={key} />
              </div>
            );
          })}
        </div>
        <div className={s.descriptionItem}>
          <input type="submit" />
        </div>
      </form>
      <div className={s.descriptionItem}>
        <ProfileStatus isOwner={isOwner} />
      </div>
    </div>
  );
};
  • Вопрос задан
  • 465 просмотров
Решения вопроса 1
WblCHA
@WblCHA
`contacts.${key as keyof typeof profile.contacts & string}`
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
26 апр. 2024, в 06:46
1500 руб./в час
26 апр. 2024, в 05:31
1000 руб./за проект