Suppose I have the following Records defined using Immutable.js:
var Address = Immutable.Record({street: \'\', city: \'\', zip: \'\'});
var User = Immutable.Reco
You can make User
subclass the Record
definition and parse address
in the constructor:
import {Record} from 'immutable'
const Address = Record({street: '', city: '', zip: ''});
class User extends Record({name: '', address: new Address()}) {
constructor({name, address} = {}) {
super({name, address: new Address(address)})
}
}
const user = new User({
name: 'Andy',
address: {
street: 'wherever',
city: 'Austin',
zip: 'TX'
}
})
console.log(user)
console.log('user.address instanceof Address:', user.address instanceof Address)
const user2 = new User({name: 'Bob'})
console.log(user2)
console.log('user2.address instanceof Address:', user2.address instanceof Address)
Output:
User { "name": "Andy", "address": Record { "street": "wherever", "city": "Austin", "zip": "TX" } }
user.address instanceof Address: true
User { "name": "Bob", "address": Record { "street": "", "city": "", "zip": "" } }
user2.address instanceof Address: true