Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Example: I have the variable person and I want to declare that the type of that variable is Person.

Like this:

var person = "idk" console.log(typeof person)  

Output: "Person"

like image 798
zLupim Avatar asked Jul 24 '20 17:07

zLupim


People also ask

Can we create a new data type?

Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building a Fraction class that works very much like the built-in numeric types: integers, longs and floats.

Can we add different data types in JavaScript?

There are two types of data types in JavaScript. JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc.

How do you create a new data type?

To create a user-defined data type. In Object Explorer, expand Databases, expand a database, expand Programmability, expand Types, right-click User-Defined Data Types, and then click New User-Defined Data Type.

Which data type is not allowed in JavaScript?

In some languages, there is a special “character” type for a single character. For example, in the C language and in Java it is called “char”. In JavaScript, there is no such type. There's only one type: string .


1 Answers

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")); 
like image 51
Pavlos Karalis Avatar answered Nov 02 '22 04:11

Pavlos Karalis