Created
September 16, 2016 13:22
-
-
Save adamrenklint/510e9590913fe4a2a4c40e4b67988735 to your computer and use it in GitHub Desktop.
Immutable data structures in TypeScript
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 { freeze, assoc } from 'icepick' | |
interface User { | |
/** | |
* Name of the user | |
*/ | |
readonly name: string | |
/** | |
* Age of the user | |
*/ | |
readonly age: number | |
} | |
const createUser = (values: User): User => freeze(values) | |
// safe constructor, check | |
const adam = createUser({ name: 'Adam', age: 33 }) | |
// safe from mutations, check | |
adam.name = 'asdas' | |
// safe from adding fields, check | |
adam.foo = 'asdas' | |
// safe reads with autocomplete, check | |
adam.age | |
// but not working, safe writes :( | |
const adam2 = assoc(adam, 'name', 123) // wrong type | |
const adam3 = assoc(adam, 'nmae', 'Adam2') // wrong key | |
type UserCollection = User[] | |
// interface ImmutableArray { | |
// push(input:void): void | |
// } | |
const createUserCollection = (users: User[]): UserCollection => freeze(users) | |
const users = createUserCollection([adam, adam2]) |
Author
adamrenklint
commented
Sep 20, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment