Last active
August 17, 2016 19:40
-
-
Save jlongster/3010fd2976f8ace4d4378c296b099a1d to your computer and use it in GitHub Desktop.
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
const t = require("tcomb"); | |
// imstruct is a tcomb type builder that internally builds an | |
// Immutable.Record object, but applies tcomb's type system to it | |
const imstruct = require("../util/imstruct"); | |
const Person = imstruct({ | |
name: t.String, | |
age: t.Number | |
}); | |
const Address = imstruct({ | |
person: Person, | |
city: t.String, | |
state: t.String | |
}) | |
// Create immutable records | |
const l = Person({ name: "James", age: 7 }); | |
console.log(l.name); // -> "James" | |
console.log(l.get("name")); // -> "James" | |
console.log(l.set("name", "sarah"); | |
// -> { name: "sarah", age: 7 } | |
// This will throw an error: `Invalid value "foo" supplied to age: Number` | |
Person({ name: "James", age: "foo" }); | |
// Create composite types | |
const addr = Address({ | |
person: Person({ name: "James", age: 7 }), | |
city: "Richmond", | |
state: "VA" | |
}); | |
console.log(addr.getIn(["person", "name"])); // -> "James" | |
console.log(addr.setIn(["person", "name"], "Sarah")); | |
// -> | |
// { person: { name: "Sarah", age: 7 }, | |
// city: "Richmond", | |
// state: "VA" } | |
// This will throw an error: | |
// `Invalid value "badAge" supplied to age: Number` | |
console.log(addr.setIn(["person", "age"], "badAge")); |
Yes, thanks! I actually meant to display James
as the output because I was showing you could access the same field in different ways.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jlongster On line 20:
console.log(l.get("name")); // -> 7
you probably meantconsole.log(l.get("age")); // -> 7
?