B
B
Black_Fire2021-07-14 01:06:26
typescript
Black_Fire, 2021-07-14 01:06:26

How to type dynamic value?

The line marked with a comment in the component example throws an error:

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'.


Component example:
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;


The place where it is invested with props:
<CustomTableCell {...{ contact, name: "name",  onChange }} />
<CustomTableCell {...{ contact, name: "lastname",  onChange }} />
<CustomTableCell {...{ contact, name: "age",  onChange }} />
<CustomTableCell {...{ contact, name: "pager",  onChange }} />


Interface example:
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;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-07-14
@Black_Fire

export interface ICustomTableCellProps {
  contact: IUser;
  cellData: keyof IUser;
  onChange: Function;
}

Must be a string or number (name, lastname, age, pager)

I don't understand where the number comes from? If you use it like this contact[cellData], then cellDataobviously it can only take key values contact, and contact- is IUser...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question