Is there any possibility to define or extend a class for a primitive type like string, number or array? For example i would like to define a Name-class which I can construct with new Name() and just returns the primitive string ""
class Name extends String {}
const name = new Name()
name === "" //this is false because String-constructor does not return a primitive string
Background:
I have a dictionary of key-value pairs, where the values are either custom classes or primitives (String, Number). I want to be able to construct an object from the class by accessing the class from the dict by the specific key:
const dict = {
"point": Point,
"area": Area,
"string": String,
"name": Name,
"number": Number,
}
const string = new dict["string"]()
string === "" //false
2
Answers
Is this what you are after?
The following just returns a new instance of the various objects from the object properties. Where new types are needed, functions define constructors for them.
No.
An
Array
is not a primitive value but an object. Yes, you can subclassArray
, but it is not recommended.Drop the
new
. Store factory functions that return the instance (or primitive value) when you call them withoutnew
: