Created
September 23, 2016 08:03
-
-
Save nikolaymatrosov/5c1235f0a7a64fa31e0f120a12a64d17 to your computer and use it in GitHub Desktop.
Typescript and Immutable.js Record usage example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Immutable from 'immutable'; | |
const UserRecord = Immutable.Record({ | |
id: '', | |
age: 0 | |
}, 'User'); | |
class User extends UserRecord { | |
public readonly id: string; | |
public readonly age: number; | |
constructor( | |
id: string, | |
age: number | |
) { | |
super({ id, age }); | |
} | |
updateId(f: (id: string) => string): User { | |
return <User>this.update('id', f); | |
} | |
updateAge(f: (age: number) => number): User { | |
return <User>this.update('age', f); | |
} | |
} | |
const john = new User('USER:JOHN', 18); | |
console.log(john); | |
// Emits error `Left-hand side of assignment expression cannot be a constant or a read-only property.` | |
// john.age = 21; | |
console.log(john); | |
const bob = john.updateId(() => 'USER:BOB').updateAge(() => 21); | |
console.log(john.id, bob.id); | |
const list = Immutable.List([john, bob]); | |
list.forEach(user => { console.log(user.age) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment