Depending on what kind of type check we want to perform, we have to choose between:
- Does a value
vhave a given primitive type – e.g.:typeof v === 'string'
- Is a value
van object (which includes objects that are not instances ofObjectsuch as the result ofObject.create(null))?v !== null && (typeof v === 'object' || typeof v === 'function')
- Is a value
vin the current realm an instance of a classCin the current realm?v instanceof C
- Is a value
vthat may be from another realm, an instance of a classCin the current realm? That can’t always be checked, but some checks work:Array.isArray(v)typeof v === 'function'
- If the class can come from another realm and the value may not come from the same realm, then we can’t perform an instance check.
The goal of this proposal is to mostly replace typeof, instanceof, and Array.isArray() with the following mechanisms:
Symbol.typeMarkerlets us assign cross-realm symbols as type markers for classes.- All built-in classes get type markers.
hasType(value, type)supports:- Checking if
valuehas a primitive type:typeis'string','null', etc. - Checking if
valueis an instance of a classtype. - Cross-realm instance checks via
Symbol.typeMarker.
- Checking if
- Two helper functions:
Object.isObject()Value.isPrimitive()
These are my first thoughts. I’m not attached to names nor many of the details.
- Can
hasType(v, Function)replacetypeof v === 'function'?
- Should the custom matchers proposed by ECMAScript Pattern Matching support
Symbol.typeMarker?