@Black_Fire

Как типизировать динамическое значение?

Строка, обозначенная комментарием в примере компонента, выдает ошибку:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IUser'.
  No index signature with a parameter of type 'string' was found on type 'IUser'.


Пример компонента:
import React, { FC, ChangeEvent } from "react";
import { TableCell, Input } from "@material-ui/core";
import { ICustomTableCellProps } from "../../types/types";
import useStyles from "../../styles.js";

const CustomTableCell: FC<ICustomTableCellProps> = ({ contact, cellData, onChange }) => {
  const classes = useStyles();
  const { isEditMode } = contact;
  return (
    <TableCell align="center" className={classes.tableBorder}>
      {isEditMode ? (
        <Input value={contact.name} name={cellData} className={classes.input} />
      ) : (
        contact[cellData] // здесь ругается typescript
      )}
    </TableCell>
  );
};

export default CustomTableCell;


Место, куда он вкладывается с пропсами:
<CustomTableCell {...{ contact, name: "name",  onChange }} />
<CustomTableCell {...{ contact, name: "lastname",  onChange }} />
<CustomTableCell {...{ contact, name: "age",  onChange }} />
<CustomTableCell {...{ contact, name: "pager",  onChange }} />


Пример интерфейсов:
export interface IUser {
  name: string;
  lastname: string;
  age: number;
  pager: number;
  id: string;
  isEditMode: boolean;
}

export interface ICustomTableCellProps {
  contact: IUser;
  cellData: string; // как типизировать? string поставил временно как заглушку. Должны приходить строка или число (name, lastname, age, pager)
  onChange: Function;
}

export interface IPrevious {
  contact?: IUser;
}
  • Вопрос задан
  • 187 просмотров
Решения вопроса 1
Aetae
@Aetae Куратор тега TypeScript
Тлен
export interface ICustomTableCellProps {
  contact: IUser;
  cellData: keyof IUser;
  onChange: Function;
}

Должны приходить строка или число (name, lastname, age, pager)

Не понял, откуда тут число? Если вы используете это так contact[cellData], то cellData очевидно может принимать только значения ключей contact, а contact - это IUser...
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы