Skip to content

Commit

Permalink
Convert lock unlock to generics (#66682)
Browse files Browse the repository at this point in the history
* Convert lock unlock to generics

* Set object type from generic for unlock

* Fix types affected by updated signature of lock/unlock

* Improve signature

* Remove expected errors no longer needed

* Restore the type for component private APIs

Co-authored-by: manzoorwanijk <manzoorwanijk@git.wordpress.org>
Co-authored-by: youknowriad <youknowriad@git.wordpress.org>
Co-authored-by: jsnajdr <jsnajdr@git.wordpress.org>
  • Loading branch information
4 people authored Nov 28, 2024
1 parent a387fbb commit 5efeef9
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions packages/private-apis/src/implementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,16 @@ export const __dangerousOptInToUnstableAPIsOnlyForCoreModules = (
* @param object The object to bind the private data to.
* @param privateData The private data to bind to the object.
*/
function lock( object: Record< symbol, WeakKey >, privateData: unknown ) {
function lock( object: unknown, privateData: unknown ) {
if ( ! object ) {
throw new Error( 'Cannot lock an undefined object.' );
}
if ( ! ( __private in object ) ) {
object[ __private ] = {};
const _object = object as Record< symbol, WeakKey >;

if ( ! ( __private in _object ) ) {
_object[ __private ] = {};
}
lockedData.set( object[ __private ], privateData );
lockedData.set( _object[ __private ], privateData );
}

/**
Expand All @@ -170,17 +172,19 @@ function lock( object: Record< symbol, WeakKey >, privateData: unknown ) {
* @param object The object to unlock the private data from.
* @return The private data bound to the object.
*/
function unlock( object: Record< symbol, WeakKey > ) {
function unlock< T = any >( object: unknown ): T {
if ( ! object ) {
throw new Error( 'Cannot unlock an undefined object.' );
}
if ( ! ( __private in object ) ) {
const _object = object as Record< symbol, WeakKey >;

if ( ! ( __private in _object ) ) {
throw new Error(
'Cannot unlock an object that was not locked before. '
);
}

return lockedData.get( object[ __private ] );
return lockedData.get( _object[ __private ] );
}

const lockedData = new WeakMap();
Expand Down

0 comments on commit 5efeef9

Please sign in to comment.