Java script object handling

Viewed 23

Are we able to restrict if a object key have int in it then the value must be a integer in JavaScript?

let myData {
dob_int: 1990
}

myData.dob_int = "a"; //need to be throw error
1 Answers

You can create a setter like this. Call the setter to set 'dob_Int' IF the value is correct.

let myData = {
    set dobInt(value){
    if(!isNaN(value)){
        console.log('Is Valid')
        this.dob_int = value
    } else {
        console.log('Is not Valid')
    }
  }
}

myData.dobInt = 'A'
//will log 'Is not Valid' and will not update the object key value
myData.dobInt = 5
//will log 'Is Valid' and will set dob_int to the value

Related