Goma_BR
Goma_BR

Reputation: 162

How to avoid being "stringly" typed in Javascript?

I've been doing a course about clean code. The course states that being "stringly" typed is a bad thing to readability and recommends using a different structure(The course uses C#):

//Dirty
if (employeeType == "manager") 

//Clean
if (employee.Type == EmployeeType.Manager)

My question is: How can I implement a structure like that in javascript?

Should I create an object like this one?

EmployeeType = {
    Manager: "manager"
}

employee = {
    Type: : "manager"
}

Is this the better way to do it?

Upvotes: 0

Views: 346

Answers (1)

Alvin Teh
Alvin Teh

Reputation: 787

If you use ES6 and classes, you can use instanceof.

class Animal {
    greet() {
      // Do nothing.
    }
}

class Dog extends Animal {
  greet() {
    console.log("Woof!");
  }
}

class Cat extends Animal {
  greet() {
    console.log("Meow!");
  }
}

let dog = new Dog();

console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!

Or in ES5:

function Animal() {
}

Animal.prototype.greet = function() {
  // Do nothing
}

function Dog() {
  Animal.call(this);
}

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.greet = function() {
  console.log("Woof!");
}

function Cat() {
  Animal.call(this);
}

Cat.prototype = Object.create(Animal.prototype);

Cat.prototype.greet = function() {
  console.log("Meow!");
}

var dog = new Dog();

console.log(dog instanceof Animal); // Returns true
console.log(dog instanceof Dog); // Returns true
console.log(dog instanceof Cat); // Returns false
console.log(dog instanceof Object); // Caveat: returns true!

Note: instanceof is not an ES6 feature, but classes are. You can use instanceof with ES5-style prototypes. For more info, see MDN

Upvotes: 2

Related Questions