Answer the question
In order to leave comments, you need to log in
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'.
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;
}
Answer the question
In order to leave comments, you need to log in
export interface ICustomTableCellProps {
contact: IUser;
cellData: keyof IUser;
onChange: Function;
}
Must be a string or number (name, lastname, age, pager)
contact[cellData]
, then cellData
obviously it can only take key values contact
, and contact
- is IUser
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question