-1

I am getting an error when trying to delete object. Currently there is no data as it is added through out other code. May issue is that I may need to delete the data if it exist. I guest I need a way to check if the data exist before deleting

Error message: TypeError: Cannot convert undefined or null to object

The error is coming from this line: delete rooms?.[roomId]?.[socket.id];

interface IDevice {
    deviceId: string;
    deviceName?: string;
    socketId: string;
    isReconnecting?: true | false;
}

const rooms: Record<string, Record<string, IDevice>> = {};

if (typeof rooms?.[roomId]?.[socket.id] !== 'undefined' && rooms?.[roomId]?.[socket.id] !== null) {
     delete rooms?.[roomId]?.[socket.id];
}
5
  • What line is the error for? Also, you shouldn't need the optional chaining within the if, as you have already checked that the properties exist. Commented Jan 19, 2023 at 20:17
  • error comes when I run this line: delete rooms?.[roomId]?.[socket.id]; Commented Jan 19, 2023 at 20:25
  • Can you share the full error trace? Commented Jan 19, 2023 at 20:27
  • Related Commented Jan 19, 2023 at 20:27
  • A simpler reproduction of the issue would be useful as well. delete null and delete undefined work fine for me. Commented Jan 19, 2023 at 20:28

1 Answer 1

0

Just remove the ?. in the delete: delete rooms[roomId][socket.id]; It tells typescript that the value might be undefined (and you cannot do delete undefined, which is the error you get). You have already checked that that the value exists, so it's fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.