How to use Object.keys() and includes() In Typescript
In this approach, To check if all enum values exist in an object, use TypeScriptâs Object.keys() and includes(). Iterate through enum keys, then verify their presence in the object. This ensures the object incorporates all enum values.
Syntax:
const allEnumValuesExist = Object.keys(EnumType).every(key =>
Object.values(yourObject).includes(EnumType[key])
);
Example: In this example, checks if all values of the Branch enum exist in the department object using Object.keys() and includes(). In this case, it returns true since the only enum value matches the departmentâs branch.
enum Branch {
CivilEngineering = "Civil Engineering",
}
const department = {
branch: "Civil Engineering",
manager: "Mukesh",
location: "Building A",
};
const allEnumValuesExist =
Object.keys(Branch).every(key =>
{
return Object.values(department).includes(Branch[key])
});
console.log(allEnumValuesExist);
Output:
true
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