API Reference
class Data
Base class for domain models. Should be extended with a set of class fields that describe the shape of desired model.
Example
import { Data } from "dataclass";
class Project extends Data {
id: string = "";
name: string = "Untitled Project";
createdBy: string = "";
createdAt: Date | null = null;
}
static create(values)
Once extended, data class can be instantiated with a new data. That's the way to get a unique immutable persistent model.
Arguments
values
(Object): POJO which shape satisfy the contract described during class extension. If you use Flow, it will warn you about the mistakes.
Returns
(Data): an instance of your data class with all the defined fields accessible as in the plain object. Properties are read only.
Example
class Vehicle extends Data {
model: string = "Unspecified";
manufacturer: string = "Unknown";
}
let vehicle = Vehicle.create({ manufacturer: "Tesla", model: "S" });
// > Vehicle { manufacturer: 'Tesla', model: 'S' }
vehicle.manufacturer;
// > 'Tesla'
method copy(values)
Create new immutable instance based on an existent one. Since properties are read only, that's the way to provide an updated model's fields to a consumer keeping the rest unchanged.
Arguments
values
(Data): POJO that includes new values that you want to change. Properties should satisfy the contract described by the class.
Returns
(Data): new instance of the same type and with new values.
Example
class User extends Data {
name: string = "Anonymous";
email: string | null = null;
}
let user = User.create({ name: "Liza" });
// > User { name: 'Liza', email: null }
let updated = user.copy({ email: "liza@example.com" });
// > User { name: 'Liza', email: 'liza@example.com' }
method equals(other)
Since immutable instances always have not equal references, there should be a way to compare the actual values.
Arguments
other
(Object): a data object of the same class as a target one.
Returns
(Boolean): false
if some field value is not strictly equal in both instances. true
otherwise.
Example
class Box extends Data {
size: number = 16;
color: string = "red";
}
let first = Box.create({ color: "green" });
let second = Box.create({ color: "blue" });
let third = first.copy({ color: "blue" });
first === second;
// > false
first === third;
// > false
first.equals(second);
// > false
second.equals(third);
// > true