How to use Object.values() and every() In Typescript
In this approach, TypeScript utilizes Object.values() and every() to confirm if all values of an enum, such as Branch, are present in an object, e.g., department. This concise method iterates through enum values, checking their inclusion in the object, ensuring completeness and adherence to predefined enum values.
Syntax:
const allEnumValuesExist = Object.values(EnumType).every(value =>
Object.values(yourObject).includes(value)
);
Example: This TypeScript example checks if all values of the Branch enum exist in the department object using Object.values() and every(). It outputs true as the object incorporates all defined enum values.
enum Branch {
CivilEngineering = "Civil Engineering",
MechanicalEngineering = "Mechanical Engineering",
ElectricalEngineering = "Electrical Engineering",
}
const department = {
branch: "Civil Engineering",
manager: "Nikita",
location: "Building A",
};
// Check if all enum values exist in the object
const allEnumValuesExist =
Object.values(Branch).every(value =>
{
return Object.values(department).includes(value)
});
console.log(allEnumValuesExist);
Output:
false
How to Check if all Enum Values Exist in an Object in TypeScript ?
To check if all values of an enum exist in an object in TypeScript, iterate through the enum values and verify their presence in the object. This ensures that the object encompasses all possible enum values, confirming completeness and adherence to the enum definition. There are various methods to check if all the enum values exist in an object which are as follows:
Table of Content
- Using Object.keys() and includes()
- Using Object.values() and every()
- Using Object.entries() and every()
Contact Us