How to declare array of specific type in javascript
var StronglyTypedArray=function(){ this.values=[]; this.push=function(value){ if(value===0||parseInt(value)>0) this.values.push(value); else return;//throw exception }; this.get=function(index){ return this.values[index] } }
EDITS: use this as follows
var numbers=new StronglyTypedArray(); numbers.push(0); numbers.push(2); numbers.push(4); numbers.push(6); numbers.push(8); alert(numbers.get(3)); //alerts 6
Array of specific type in typescript
export class RegisterFormComponent { genders = new Array<GenderType>(); loadGenders() { this.genders.push({name: "Male",isoCode: 1}); this.genders.push({name: "FeMale",isoCode: 2}); }}type GenderType = { name: string, isoCode: number }; // Specified format
If simply you want to restrict user to push values as per first value entered you can use below code
var stronglyTypedArray = function(type) {this.values = [];this.typeofValue;this.push = function(value) { if(this.values.length === 0) { this.typeofValue = typeof value; this.pushValue(value); return; } if(this.typeofValue === typeof value) { this.pushValue(value); } else { alert(`type of value should be ${this.typeofValue}`) }}this.pushValue = function(value) { this.values.push(value);}
}
If you want to pass your own type, you can customize the above code a bit to this
var stronglyTypedArray = function(type) {this.values = [];this.push = function(value) { if(type === typeof value) { this.pushValue(value); } else { alert(`type of value should be ${type}`) }}this.pushValue = function(value) { this.values.push(value);}
}