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

Rule proposal: prefer Symbol.for() over Symbol() #2027

Closed
Xunnamius opened this issue Jan 24, 2023 · 3 comments
Closed

Rule proposal: prefer Symbol.for() over Symbol() #2027

Xunnamius opened this issue Jan 24, 2023 · 3 comments
Labels

Comments

@Xunnamius
Copy link

Description

From time to time I find myself passing things between realms, usually in Node/Jest but also between workers or frames on the frontend, and I've been bitten by faulty instanceof checks (identity discontinuity) more than once. My solution has been to use Symbols to track an object's type/provenance.

For instance, for a piece of code meant to handle a subset of custom app errors, instead of catch(e) { if(e instanceof AppError) ... } I'll do catch(e) { if(e?.[$type] === 'AppError') ... } where const $type = Symbol('type') and class AppError extends Error { [$type] = 'AppError'; ... }.

However, unlike the well-known Symbols, custom Symbols are only unique at the realm level and so suffer the same identity discontinuity issue as instanceof. But we can create cross-realm Symbols with Symbol.for. Perhaps Symbol.for() should be preferred over Symbol() in all cases?

Fail

const foo = Symbol('foo');

Pass

const foo = Symbol.for('foo');
const foo = Symbol.for('@Xunnamius/foo');

Additional Info

N/A

@fisker
Copy link
Collaborator

fisker commented Jan 24, 2023

They are for different purposes.

As for the instanceof problem, you may want try Ergonomic brand checks for Private Fields

@Xunnamius
Copy link
Author

I see. Thanks for the link

@sindresorhus
Copy link
Owner

Passing on this as it's not the correct use of Symbol.for.

@sindresorhus sindresorhus closed this as not planned Won't fix, can't repro, duplicate, stale Mar 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants