TypeScript notes

To change type of a property in a new type first delete the property using Omit and then add it again. Below example changes type of _id from string to ObjectId:

type ReservationItem = {
    _id: string;
    label: string;
}

type ReservationItemDB = Omit<ReservationItem, '_id'> & {
    _id: ObjectId;
    timestamp: Date;
}

You can define type of documents read from a MongoDB collection like this:

const reservations = database.collection<ReservationItem>('reservations');

Fixing TypeScript error property does not exist on type EventTarget

When working with event listeners in TypeScript one often runs into error that a particular property does not exist on type EventTarget. While it's relatively easy to fix this error using type "any" or by typecasting the event target using "as", none of these solutions are optimal since they simply disable TypeScript's type checking, which is what we are using TypeScript for in the first place!

The better way to fix this error is to use JavaScript's instanceof operator which you can read about at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof.

Example of code that throws error:

document.querySelector('p').addEventListener('click', (event) => {
    alert(event.target.textContent);
});

Error:

Property 'textContent' does not exist on type 'EventTarget'.

Solution:

document.querySelector('p').addEventListener('click', (event) => {
    if (event.target instanceof Element) {
      alert(event.target.textContent);
    }
});