Ensuring action type safety with Object.create(null)
Use Object.create(null) to create a map of action types, removing concerns of prototype methods interference.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Action Types Example</title>
<style>
/* Your CSS styles here */
body {
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div id='app'>
<button id='actionButton'>Perform Action</button>
</div>
<script>
// Create an object without prototype
const ActionTypes = Object.create(null);
// Define action types
ActionTypes.ADD_ITEM = 'ADD_ITEM';
ActionTypes.REMOVE_ITEM = 'REMOVE_ITEM';
// Handler function that utilizes the safe action types
function handleAction(type) {
switch (type) {
case ActionTypes.ADD_ITEM:
console.log('Adding item');
// add item logic
break;
case ActionTypes.REMOVE_ITEM:
console.log('Removing item');
// remove item logic
break;
default:
console.error('Unknown action type');
}
}
// Event listener for button click
document.getElementById('actionButton').addEventListener('click', function() {
handleAction(ActionTypes.ADD_ITEM);
});
</script>
</body>
</html>
This HTML document includes inline CSS for basic styling and a JavaScript block that creates a map of action types using Object.create(null) to avoid prototype pollution. The 'ActionTypes' object is used to store different action types as strings. An event listener is added to a button that, when clicked, calls the 'handleAction' function with one of the action types from this map, ensuring type safety since it doesn't inherit from Object.prototype.