Skip to content

Instantly share code, notes, and snippets.

@jlongster
Last active August 17, 2016 19:40
Show Gist options
  • Save jlongster/3010fd2976f8ace4d4378c296b099a1d to your computer and use it in GitHub Desktop.
Save jlongster/3010fd2976f8ace4d4378c296b099a1d to your computer and use it in GitHub Desktop.
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"));
@kpuputti
Copy link

@jlongster On line 20: console.log(l.get("name")); // -> 7 you probably meant console.log(l.get("age")); // -> 7 ?

@jlongster
Copy link
Author

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