From 99edc2b2c55c4708ac59bb82cbd8f1bb402f8f9f Mon Sep 17 00:00:00 2001 From: Manzoor Wani Date: Thu, 28 Nov 2024 07:45:13 -0800 Subject: [PATCH] Convert lock unlock to generics (#66682) * 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 Co-authored-by: youknowriad Co-authored-by: jsnajdr --- packages/private-apis/src/implementation.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/private-apis/src/implementation.ts b/packages/private-apis/src/implementation.ts index bae53bae8d158a..5a5fb3f39fa183 100644 --- a/packages/private-apis/src/implementation.ts +++ b/packages/private-apis/src/implementation.ts @@ -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 ); } /** @@ -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();