core icon indicating copy to clipboard operation
core copied to clipboard

feat(reactivity): strictMode option for readonly and shallowReadonly

Open claudiaballano opened this issue 2 years ago • 1 comments
trafficstars

Strict Mode Option to readonly and shallowReadonly

This PR introduces a strictMode option to the readonly and shallowReadonly functionalities, enhancing safety when handling readonly variables. With strict mode enabled, attempting to mutate a readonly variable will result in an error, providing immediate feedback to developers instead of a console warning.

Motivation:

Enabling strict mode in readonly and shallowReadonly it will be beneficial for large projects with complex data structures, it ensures data integrity and boosts code predictability, reducing the risk of subtle bugs caused by mutable readonly variables. Additionally, by throwing an error, this will help advanced debugging tools to track and analyse these attempted mutations.

Changes

The readonly and shallowReadonly functions have been updated to include a new parameter:

export function readonly<T extends object>(
  target: T,
  strictMode?: StrictMode
): DeepReadonly<UnwrapNestedRefs<T>> {
  return createReactiveObject(
    target,
    true,
    readonlyHandlers(strictMode),
    readonlyCollectionHandlers,
    readonlyMap
  )
}

Usage Example


const state = readonly({ count: 0 }, {strict: true}); // Enabling strict mode

try {
  state.count = 10; // Throws an error in strict mode, preventing accidental mutation
} catch (error) {
  console.error('Error:', error.message); // Output: "Error: Cannot assign to read-only property 'count' of object '#<Object>'"
}

The strictMode parameter is optional and can be set to one of the following values:

  • true: In strict mode, any attempt to mutate a readonly variable will throw an error. This helps explicitly track all mutation intents, making debugging more straightforward.

  • false (default): If strictMode is not provided or set to false, the previous behavior without strict mode will be maintained.

Related Issues

[Closes #8919] (if applicable)

Thank you! 😄

claudiaballano avatar Aug 05 '23 10:08 claudiaballano

Requests for API changes like this should go through RFC to scope out possible issues.

pikax avatar Oct 20 '23 10:10 pikax