Structure
Structure v2
Structure v2
  • Introduction
  • Schema concept
    • Shorthand and complete attribute definition
    • Circular reference
    • Nullable attributes
  • Custom setters and getters
  • Coercion
    • Primitive type coercion
    • Arrays coercion
    • Generic coercion
    • Recursive coercion
    • Disabling coercion
  • Validation
    • String validations
    • Number validations
    • Boolean validations
    • Date validations
    • Array validations
    • Attribute reference
    • Nested validations
    • Validate raw data
  • Strict mode
  • Cloning an instance
  • Serialization
  • Testing
  • Battlecry generators
  • Migrating from v1
  • Support and compatibility
  • Changelog
  • Contributing
  • License
  • GitHub
Powered by GitBook
On this page

Was this helpful?

  1. Coercion

Recursive coercion

Structure also does recursive coercion so, if your declared type is Array or other Structure, the items/attributes of the raw value will be coerced as well:

class BooksCollection extends Array {}

const Book = attributes({
  name: String,
})(class Book {});

const User = attributes({
  favoriteBook: Book,
  books: {
    type: BooksCollection,
    itemType: Book,
  },
})(class User {});

const user = new User({
  favoriteBook: { name: 'The Silmarillion' },
  books: [{ name: '1984' }],
});

user.favoriteBook; // Book { name: 'The Silmarillion' } => coerced plain object to Book
user.books; // BooksCollection [ Book { name: '1984' } ] => coerced array to BooksCollection and plain object to Book
PreviousGeneric coercionNextDisabling coercion

Last updated 4 years ago

Was this helpful?