I'm displaying a list that I fetch from the backend, which uses ints as ids:
const events = [
{ id: 1, name: "Event 1" },
{ id: 2, name: "Event 2" }
];
In the UI, I can select an event, or I have no event selected. I prefer keeping the same type for the selected event and I know that my DB will not generate negative ids for its rows. So I use a common convention of -1 as initial / unselected event:
const selectedEvent = useState<number>(-1)
Now, I want to add a Start and End event to the event list, which are "event-like" objects, that I did not get from the same DB table. I need to assign an id to them.
Positive numbers are possibly used by the DB. I'll just stay away from zero for other reasons**. So I come up with negative indices starting from -2:
const events = [
{ id: -2, name: "Start Event", payload: "ABC" },
...events,
{ id: -3, name: "End Event", payload: "XYZ" }
];
This works fine, only I'm wondering, is this a commonly used convention? Will other devs, or future me, understand this code or will they pull their hair out if they see this? If it's not the best way forward, which is? (As you see, I'm working with a javascript / typescript codebase, so if it matters, it's specifically about this ecosystem)
** I'm not 100% sure that every DB will not start numerical indices with 0. There is only one 0, and I need two ids. 0 is falsey in javascript, which may cause some problems along the road. Long story short, I'll skip zero :)
Edit: To answer some of the comments:
declare type Event = {
id: number;
name: string;
payload: string;
};
declare type StartOrEnd = {
id: number;
name: string;
isStart: boolean;
}
However, the user does want to navigate the events as well as the start and the end as an event. This is not ideal from a type perspective, but this is where I will have to give in a bit, one way or another. My UI simply takes an object and needs it to have an id and a name:
interface Props {
id: number;
name: string;
selectEvent: (id: number) => void;
}
const renderEvent = ({id, name, selectEvent}) => {
return (
<div onClick={() => selectEvent(id)}>{name}</div>
)
}