NodeJS and Class limitations

Viewed 126

I am wondering if there is a way to handle the following scenarios in a CLASS in NodeJs. I have a class lets call it contact which has a bunch of string fields but also has for example an array of email class. How can i specify in JavaScript that a value should be actually an Array of another class since i cant specify data type in JavaScript. Also how can i restrict the value in a field in a class, for example my email class has a field called type which can either be "home|work|other"

2 Answers

With "vanilla" Javascript, there is no specific way to tell an Array that it should be filled only with objects of another specific class. An array (and any other data structure, really) will accept basically whatever you throw it. This is perfectly valid JS (though in general you wouldn't often do something like this):

var array1 = [1, 'two', {three: true}, [4]];

If you are interested in type safety, you can check out something like Typescript, but it isn't required and can make things more complicated if you're just learning how the JS ecosystem works.

Although Javascript is not going to give you static typing, since you're using Node and have some control over which version you are using you do have some other options. You can use a Proxy. If your email array is a proxy, you can control the setter and only allow what you want to be added. For example (not sure this snippet will run in all browsers):

class Email {
  constructor(addr) {
    this.address = addr
  }
}

// proxy array to check for values on set
let emails = new Proxy([], {
  set: function(target, property, value, receiver) {
    if (!(value instanceof Email)) {
      if (property != "length")
        console.log(`Array can only contain Email instances "${value}" is an incompatible type`)
      return true
    }
    target[property] = value;
    return true;
  }
});

// fails
emails.push(1)
console.log("current array:", emails)

// works
let e = new Email("test@example.com")
emails.push(e)
console.log("current array:", emails)

// fails
emails[0] = "test"
console.log("current array:", emails)

Related