How to ensure that type of value assigned to a class instance property is the requested one? Still NEED HELP 10/28


#1

Hello,

So, we can create setters to be sure that when we reassign a property its value’s type will be the one requested. But, I wanted to do the same with the first property values assigned to a class instance. Is it possible? ??

Here is my situation:

class School {
  constructor (name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    this._numberOfStudents = numberOfStudents;
  }
}

class Middle extends School {
  constructor (name,level,numberOfStudents) {
    super (name,level,numberOfStudents);
  }
}

const excel = new Middle ('Excel', 'Middle', false); 
/*numberOfStudents parameter should be a number value, 
so I want this instance creation to throw an error in this kind 
of a case.*/

console.log(excel.numberOfStudents) // prints "false" 

#2

I’m not sure if there is a better way to do this, but you could put checks in like:

class School {
  constructor (name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    if ((typeof numberOfStudents === 'number')
        this._numberOfStudents = numberOfStudents;
    else
        throw "Parameter is not a number!";
  }
}

I made a spelling mistake, should be typeof


#3

Thanks for reply but, unfortunately, I don’t think this works. Is this something you use? I could put this syntax in a setter but it doesn’t work in the middle of property list.


#4

I still need help. What is with that a thousand new FAQ topics? It pushed my question very deep…


#5

@dugong-s

Maybe it is SyntaxError? Try

class School {
  constructor (name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    if (typeof numberOfStudents === 'number') {
        this._numberOfStudents = numberOfStudents;
    } else {
        throw "Parameter is not a number!";
  }
}
}

const midschool= new School('name', 8, 'hi');

I ran it several times inside the console and tried to fix all syntax errors. I ended up at “Uncaught Parameter is not a number!”, which might be something to be fixed, but if you wanted to use throw, that could work. Or you could replace throw with a console.log(), as in

class School {
  constructor (name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    if (typeof numberOfStudents === 'number') {
        this._numberOfStudents = numberOfStudents;
    } else {
        console.log("Parameter is not a number!");
  }
}
}

const midschool = new School('name', 8, 'hi');

#8

@dugong-s

I used your code and edited some stuff, here’s what I end up with. It gives you an error and says 'Parameter is not a number'

class School {
  constructor (name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    if (typeof numberOfStudents === 'number') {
        this._numberOfStudents = numberOfStudents;
    } else {
        throw "Parameter is not a number!";
  }
}
}

class Middle extends School {
  constructor (name,level,numberOfStudents) {
    super (name,level,numberOfStudents);
  }
}

const excel = new Middle('Excel', 'Middle', false); 

console.log(excel.numberOfStudents) //It prints an error now

#9

Wait, I see what you mean by “it doesn’t work”. It returns undefined if it is a number… lemme go check code…


#10

Thanks for your effort.
But I need that error to pop when you have tried to assign it an void argument for numberOfStudents parameter. I want to cease class creation process if you put in an invalid argument.


#11

I see… first of all, I have a question - what stops class creation?


#12

I am trying to find it out as an outcome of this topic.


#13

Is there anybody can help me on this issue?


#14

You’ll have to wait. Some questions go unanswered for quite some time. Hopefully someone who can help you will find this thread in the near future.


#15

@dugong-s What are you trying to accomplish? Why do you want to limit it to numbers?


#16

The point is not limiting “the parameter” to numbers. I am just trying to understand if there is a way to check the argument that somebody would enter for a new class parameter. Because in this example it is obvious that you should enter numbers but it could be like this:
Let’s say that you have above program to create a catalog of schools in your neighborhood. I, as your programmer, have already created a class called ‘Middle School’ and its parameters are name, level, numOfStudents. You launch the program, try to create a class for some school and you enter 'Excel Middle School', 8, 320.

So, you thought you should enter the highest class level within the school for the level parameter (because you were just confused), but you shouldn’t. It was for the school’s level, which is 'Middle School'. So, I want to tell the user that they did a mistake, they should write a 'String' value includes the school level.

Hope you have an answer for me.


#17

JavaScript variables are not type safe, that is how they are created, so using typeof is the only method that I’m aware of, unless you want to hardcode the types and compare them like this:

if (level === 'elementary school' || level === 'middle school' || level === 'high school') {
    this._level = level;
}
else {
    throw "Enter the school level as text. (Example: Middle School)";
}

This will probably be the most accurate way to do it, because it only allows those values as correct values.

The other way is with typeof:

class School {
	constructor (name,level,numberOfStudents) {
		this._name = name;
		if (typeof level === 'string')
		{
			this._level = level;
		} else {
			throw "Enter the school level as text. (Example: Middle School)";
		}
		if (typeof numberOfStudents === 'number') {
			this._numberOfStudents = numberOfStudents;
		} else {
			throw "Parameter is not a number!";
		}
	}
}

This method just check if it is a string value.

If your input is a form on a website, it would be better to give the options in a combobox (drop down list):

<select>
  <option value="elementary">Elementary School</option>
  <option value="middle">Middle School</option>
  <option value="high">High School</option>
</select>

This makes it easier to pick a valid option, but if a user wants to be malicious they can still inspect the element and edit the values.


#18

That helped a lot! Thanks. Actually, your first reply contains the same information, but when I tried it (after correcting missing syntax) it didn’t work. I don’t know why. And, it didn’t seem logical to me to type an if statement for a property before assigning a property. However, it works, I was confused.
Thanks again!