-
-
Save PetrSnobelt/7ffa539bcdb0ae63a282ffd4e5382976 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")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment