You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
constfoo=Symbol('foo');
Pass
constfoo=Symbol.for('foo');
constfoo=Symbol.for('@Xunnamius/foo');
Additional Info
N/A
The text was updated successfully, but these errors were encountered:
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 docatch(e) { if(e?.[$type] === 'AppError') ... }
whereconst $type = Symbol('type')
andclass 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 withSymbol.for
. PerhapsSymbol.for()
should be preferred overSymbol()
in all cases?Fail
Pass
Additional Info
N/A
The text was updated successfully, but these errors were encountered: