1

How can a JS array be limited to one type? E.g. string.

Say I have the following code:

const arr = [];
arr.push('this is a string'); // accept
arr.push('I do not want numbers in this array'); // accept
arr.push(5); // reject - it's not a string!

How can I reject the last push or any other push that attempts to add a variable which is not of type string? The only way I can think of is to make a custom class which extends Array and overrides functions, such as push, to check the type of the element being added and throw an error if not of type string. However, this seems pretty nuclear and bug-prone!

4
  • 1
    You're looking for TypeScript. Commented Aug 8, 2018 at 21:22
  • Just create a function in a utility file that you can run to check types and then push if the type check passes. Then use that function in place pf the normal push method. Simple. Commented Aug 8, 2018 at 21:23
  • You can try Proxies. Commented Aug 8, 2018 at 21:30
  • @goastler Just use typed arrays: developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays Commented Aug 9, 2018 at 8:47

4 Answers 4

2

Generate a new constructor that inherits from Array.

function array2 (){
    var obj = [];
    Object.setPrototypeOf(obj,array2.prototype);
    return obj;
}

array2.prototype = Object.create(Array.prototype);

array2.prototype.push = function(){
    if(Array.prototype.slice.call(arguments).some(function(d,i){return typeof d !== "string"})){
        return;
    }
    return Array.prototype.push.apply(this,arguments);
}

var u = new array2;
u.push(3); //u still empty;
u.push("3"); //returns 1, u is ["3"];

You can modify and throw if you want. etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha! That's what I'm looking for! :)
1

I would recommend using TypeScript if you want to add type safety to your Javascript. Below is a function you may use though to ensure what you push is the correct type

const pushType = (arr, value, type) => {
  if (typeof value === type) {
    arr.push(value);
  }
};

pushType(['a', 'b'], 'c', 'string');

Comments

0

Extend Array class to modify push function such as below

   class StringArray extends Array {
      constructor(){
       super();
      }
      push(d){
        if(typeof d === "string"){
           this[this.length] = d;
        }
      }
    }

it will push only string type data

var arr = new StringArray();
arr.push(1) // won't push
arr.push("1") //pushed

Comments

-1

You can add type validation. Using the 'typeof' keyword you will get the operand's type as a string, e.g. "number", "boolean", "undefined". Validate this prior to adding the value to your array.

3 Comments

He's obviously looking for something more automatic than adding checks everywhere that he adds to the array.
How is that 'obvious' when all of the other answers do the same.
The other answers define a function or class wrapper to automate it. If that's what you meant, it wasn't clear to me without any code examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.