1.0.0 • Published 7 years ago

ts-immutable-struct v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
7 years ago

ts-immutable-struct

npm version NPM downloads Build Status

ts-immutable-struct is a TypeScript package for using immutable.js with type-safe cursors and simple event tracking to allow distinguishing between user-initiated state changes and internal state changes (e.g. to sync state).

The emphasis here is on type-safety.

This package is inspired by immstruct, but uses references for everything.

React users will want to combine this with ts-react-struct, so shouldComponentUpdate() works with ts-immutable-struct cursors.

Getting started

Install the package:

npm install --save ts-immutable-struct

Initialize the global state struct:

import {Struct} from 'ts-immutable-struct'

let data = Struct({
  a: 5,
  b: 'hey',
  c: null as string | null,
  d: [1, 2, 3],
  e: [true, true, false],
  f: ['a', 'b', 'c'],
  g: [{a: 40, b: ['d']}, {a: 50, b: ['e']}],
  l: [[60]],
  o: {f: 65},
  da: new Date(),
})

data.observe((event, oldVal, newVal) => {
  // Handle state changes (oldVal and newVal are both cursors, so you'll need to deref())
})

Note that Struct() will internally convert the given argument to an immutable.js object using immutable.fromJS().

Here's how to traverse and mutate the Struct state:

// retrieve a value
let a = data.get('a').deref()

// update a value
data.get('g').get(0).get('a').val(99)

// alternative
data.get('g').get(0).get('a').update(x => x + 1)

// update the underlying immutable.js value
data.get('g').get(0).update(x => x.set('a', 99))

Everything here is type-checked. A wrong property name or type results in a compile-time error.