Depending on what kind of type check we want to perform, we have to choose between:
- Does a value
v
have a given primitive type – e.g.:typeof v === 'string'
- Is a value
v
an object (which includes objects that are not instances ofObject
such as the result ofObject.create(null)
)?v !== null && (typeof v === 'object' || typeof v === 'function')
- Is a value
v
in the current realm an instance of a classC
in the current realm?v instanceof C
- Is a value
v
that may be from another realm, an instance of a classC
in 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.typeMarker
lets us assign cross-realm symbols as type markers for classes.- All built-in classes get type markers.
hasType(value, type)
supports:- Checking if
value
has a primitive type:type
is'string'
,'null'
, etc. - Checking if
value
is 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
?