Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert lock unlock to generics #66682

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading