I have a MaterialTable component and I added the editable
attribute to it. For onRowUpdate
and onRowDelete
methods, I want to get the index of the updated or removed item.
This is the minimal reproducible sandbox: https://codesandbox.io/s/busy-fast-z84qq?file=/src/App.tsx
I got the error when I obtained the index of the item. Should I include the tableData
property to my IPerson
interface? How can I overcome this problem?
CodePudding user response:
Should I include the tableData property to my IPerson interface?
No, because you will probably use your IPerson
interface throughout your application, and adding a tableData
property that may or may not exist (see below) will defeat the purpose of typechecking. Typescript is telling you that tableData
doesn't exist on your IPerson
interface, which is correct. However, the underlying Javascript from your dependency has appended your object with a tableData
property for its own internal purposes (and external if this is the only way to get at the index) and didn't bother to let Typescript know. Your code runs, the index is available for use.
There are probably better ways to do this, but you could create an IPersonAfterRowUpdate
interface that has the tableData object on it:
interface IPersonAfterRowUpdate extends IPerson {
tableData: { id: number };
}
/* ... */
onRowUpdate: (newData, oldData) =>
new Promise<void>((resolve, _reject) => {
setTimeout(() => {
if (oldData) {
const updatedData = [...data];
const index = (oldData as IPersonAfterRowUpdate).tableData.id;
updatedData[index] = newData;
setData(updatedData);
resolve();
}
_reject(new Error('Could not find oldData'));
}, 1000);
}),
Notice we have to check that oldData
exists otherwise TS wouldn't like us indexing updatedData
with a possible undefined
value.
Then submit a PR to this library with this function typed correctly!