Как в React, Typescript передать в зависимости от типа пропсов объект тому или иному вложенному компоненту?

У меня есть компонент, в который я передаю через пропсы массив объектов юнион типа:

export interface IAdminInstanceFormState {
  instances: (IMaterial | IService)[];
}

Мне нужно в зависимости от того какого типа массив передать его дальше, тому или иному компоненту:

const AdminInstanceForm: FC<IAdminInstanceFormState> = ({ instances }) => {
return (
    <div>      
        <div>
          <FormService
            service={
              instances.filter((instance) => instance.name === showForm)[0]
            }
            hideFormHandler={hideFormHandler}
          />
          <FormMaterial
            material={
              instances.filter((instance) => instance.name === showForm)[0]
            }
            hideFormHandler={hideFormHandler}
          />          
        </div>      
    </div>
  );
};

Я пытался сделать это через generics props, но это не помогло. Выдавал ошибку "Type 'T' is not assignable to type IService:

const AdminInstanceForm = <T,>({
  instances,
}: IAdminInstanceFormState<T>): ReactElement => {
  
  const [showForm, setShowForm] = useState<any>(null);

  const hideFormHandler = () => {
    setShowForm(null);
  };

  return (
    <div>      
      <FormService
          service={
            instances.filter((instance) => instance.name === showForm)[0]
          }
          hideFormHandler={hideFormHandler}
      />
      <StyledButton type="button" onClick={hideFormHandler}>
        Отмена
      </StyledButton>
    </div>
  );
};

export interface IAdminInstanceFormState<T> {
  instances: T[];
}

Полностью код выглядит так:

const AdminInstanceForm = <T,>({
  instances,
}: IAdminInstanceFormState<T>): ReactElement => {
  useEffect(() => {
    setInstanceName(instances[0]?.name);
  }, [instances]);

  const [instanceName, setInstanceName] = useState('');
  const [showForm, setShowForm] = useState<any>(null);

  const instanceSelectHandler = (e: ChangeEvent<HTMLSelectElement>) => {
    if (showForm) {
      setInstanceName(e.target.value);
      setShowForm(e.target.value);
    } else {
      setInstanceName(e.target.value);
    }
  };

  const addInstanceHandler = () => {
    setShowForm('');
  };

  const changeInstanceHandler = () => {
    setShowForm(instanceName);
  };

  const hideFormHandler = () => {
    setShowForm(null);
  };

  return (
    <div>
      <StyledSelect
        name="services"
        id="services"
        onChange={instanceSelectHandler}
      >
        {instances.map((instance, index) => (
          <option key={instance.name + index}>{instance.name}</option>
        ))}
      </StyledSelect>
      <StyledButton type="button" onClick={addInstanceHandler}>
        Добавить Услугу
      </StyledButton>
      <StyledButton type="button" onClick={changeInstanceHandler}>
        Изменить
      </StyledButton>
      {showForm !== null && (
        <div>
          <FormService
            service={
              instances.filter((instance) => instance.name === showForm)[0]
            }
            hideFormHandler={hideFormHandler}
          />
          <StyledButton type="button" onClick={hideFormHandler}>
            Отмена
          </StyledButton>
        </div>
      )}
    </div>
  );
};

Подскажите, пожалуйста, как решить проблему?


Ответы (0 шт):