Reputation: 16729
I have this function which tests that an object has certain fields
validateServerResponseStructure(res: any) {
let isTypeCorrect: boolean = (
res.result != undefined) && (res['additional-info'] != undefined
);
return isTypeCorrect;
}
Is there a way to test that res
has only result
and additional-info
properties and nothing else?
Upvotes: 0
Views: 929
Reputation: 370639
Just check that the length of its keys
is exactly two. Also, probably best to use strict equality comparison, if you want to ensure that the properties are not undefined
:
validateServerResponseStructure(res: any) {
let isTypeCorrect: boolean = (
res.result !== undefined
&& res['additional-info'] !== undefined
&& Object.keys(res).length === 2
);
return isTypeCorrect;
}
In the unusual case that you may have properties that contain the undefined
value, and you want to permit such values, check the length of the keys, and that both result
and additional-info
are included in the keys:
const keys = Object.keys(res);
let isTypeCorrect: boolean = (
['result', 'additional-info'].every(key => keys.includes(key))
&& keys.length === 2
)
Upvotes: 2