I am trying to get an idea how to build javascript class
that would represent an object like Person
.
class Person {
constructor(name, age, hobbies) {
this.name = name; // string
this.age = age; // number
this.hobbies = hobbies; // array
}
}
This object will be used in react/redux-form
to map ining and outgoing data from/to database
. My question is how can I enforce hobbies
are really array
type or age
as number
and name
as string
in its class definition? In java
, I am allowed to build simple data model via strong type of its property (e.g. String name = null)
and having getter/setter
method for it.
I am trying to get an idea how to build javascript class
that would represent an object like Person
.
class Person {
constructor(name, age, hobbies) {
this.name = name; // string
this.age = age; // number
this.hobbies = hobbies; // array
}
}
This object will be used in react/redux-form
to map ining and outgoing data from/to database
. My question is how can I enforce hobbies
are really array
type or age
as number
and name
as string
in its class definition? In java
, I am allowed to build simple data model via strong type of its property (e.g. String name = null)
and having getter/setter
method for it.
- 1 does it have to be in JS? or can you use TypeScript instead? (and then transpile it) – blurfus Commented Jul 29, 2019 at 19:28
- unfortunately I am locked to use only JS. – DaeYoung Commented Jul 29, 2019 at 19:31
- you don't need any library or TypeScript or whatever to fulfil your requirement. JavaScript actually provides features to acplish them and more. I'll demonstrate it in a new answer. – Igwe Kalu Commented Jul 29, 2019 at 20:03
5 Answers
Reset to default 4if you're not using typescript or some sort of typing library then you have to manage it yourself. So in your example:
class Person {
constructor(name, age, hobbies) {
name = typeof name === 'string'?name:null;
age = typeof age === 'number'?age:null;
hobbies = Array.isArray(hobbies)?hobbies:null;
...
}
}
You might want to do some more in depth checking but this will get you going.
Javascript is a dynamically typed language which means , the errors occur only once the program is executed. That is, at runtime. This means that a program written in a dynamically-typed language can pile even if it contains type errors that would otherwise prevent the script from running properly.
You'll need to use Typescript for that in react,and it's possible to write react apps in Typescript. Typescript a strict syntactical superset of JavaScript, and adds optional static typing to the language. TypeScript is designed for development of large applications and transpiles to JavaScript
Other than typing getters/setters are supported in JS
You can use the typeof operator along with indexOf() to do validation.
class Person {
constructor(name, age, hobbies) {
let hobbyList = ["sports", "cooking", "movies"];
if(typeof name !== "string"){
throw "Name must be a string!";
} else {
this.name = name;
}
if(typeof age !== "number"){
throw "Age must be a number!"
} else {
this.age = age;
}
if(hobbyList.indexOf(hobbies) <=0){
throw "Must be a choice from the list"
} else {
this.name = name;
}
}
}
let p1 = new Person(12,"twelve", "archery"); // all args are bad - 3 errors
let p2 = new Person("Scott", 52, "movies") // good - no errors
Aside from validation on instantiation of the object. Further validation can be done via a setter (as you required) when the property value changes:
class Person {
constructor(name, age, hobbies) {
if (!Array.isArray(hobbies)) {
console.error(`Type of hobbies should 'array', found ${typeof hobbies}`);
}
Object.defineProperties(this, {
age: {
get: () => age,
set: value => {
age = value;
}
},
name: {
get: () => name,
set: value => {
name = value;
}
},
hobbies: {
get: () => hobbies,
set: value => {
if (!Array.isArray(value)) {
console.error(`Type of hobbies should 'array', found ${typeof value}`);
}
hobbies = value;
}
}
});
}
}
Hence, the following will throw an error
const person = new Person ( "Me", 465, "not a list of hobbies" );
It's that simple. Learn more at Object.defineProperties.
class Person {
constructor(name, age, hobbies) {
this.name = name; // string
this.age = age; // number
this.hobbies = hobbies; // array
}
setName(name){
console.log(typeof name=="string")
if(typeof name=="string")
this.name = name;
}
setAge(age){
if(typeof age=="number")
this.age = age;
}
}
let person = new Person('Rahi','45',["dfdsf","dd"])
console.log("....name=%s, age=%s",person.name,person.age);
person.setName("John");
console.log("....name=%s",person.name);
person.setName(9999);
console.log("....name=%s",person.name);
console.log("................");
person.setAge("45");
console.log("....name=%s",person.name);
person.setAge(45);
console.log("....name=%s",person.name);
console.log("....name=%s, age=%s",person.name,person.age);
You can check type of on set method to set correct value type.