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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With