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"
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.
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.
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.
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 .
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With