Is it possible to create a new data type in JavaScript?

There are only a few return values of typeof as listed here:

Undefined         "undefined"
Null              "object" (see below)
Boolean           "boolean"
Number            "number"
BigInt            (new in ECMAScript 2020)    "bigint"
String            "string"
Symbol            (new in ECMAScript 2015)    "symbol"
Function object   (implements [[Call]] in ECMA-262 terms)    "function"
Any other object  "object"

So as per your question, you can't have your own value for typeof operator. And if you create your own object with class or function() its type will be an object.


The closest you can get to what you're describing is testing instanceof, or using instanceof to create your own type checking function:

class Person {
  constructor(name, age) {
    this.name = name; 
    this.age = age;
  }
}

const bill = new Person("Bill", 40);

function checkType(data){
  if(data instanceof Person) return "Person";
  return typeof data; 
}

console.log(bill instanceof Person);
console.log(checkType(bill));
console.log(checkType("bill")); 

Tags:

Javascript