Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that a partial is full at runtime

Tags:

typescript

My function takes argument meOrPartial which is typed as Partial<IMe> | IMe. In the body of my function I need to detect if it is "full", is there a way to do this at runtime?

I tried this pseudocode (IMe has much more keys than this):

interface IMe {
   id: string;
   isActive: boolean;
}

function (meOrPartial: Partial<IMe> | IMe) {
   const meKeys = keyof IMe;
   // const meKeys = K in IMe;
   const isFull = Object.keys(meKeys).every(key => meOrPartial.hasOwnProperty(key));

}

Of course this doesn't work, but is there a way to do this check in runtime?

like image 981
Noitidart Avatar asked Dec 16 '25 20:12

Noitidart


1 Answers

TypeScript interfaces are not runtime artifacts and so there is not much you can do without also defining some sort of object that contains all the keys you are checking for.

With that in mind, I would do something like this:

const MeTemplate: IMe = {
  id: '',
  isActive: false,
  ...
};

And then your isFull function would look like this:

function isFull(obj) {
  return Object.keys(MeTemplate).every(prop => prop in obj);
}

It's less than ideal that you need to define the keys of IMe twice, but this is mitigated by assigning MeTemplate a type of IMe. This ensures that if you change the shape of IMe, you will have a compiler error until you also change MeTemplate.

like image 130
Andrew Eisenberg Avatar answered Dec 19 '25 20:12

Andrew Eisenberg