/ examples / default_value.ts
default_value.ts
 1  import { defaultValue, deserialize, t } from "../src";
 2  
 3  // We'll keep a counter aside.
 4  let i = 0;
 5  
 6  class MyModel {
 7    @defaultValue(() => new Date())
 8    createdAtInstance = t.instance(Date);
 9  
10    @defaultValue(Date.now)
11    createdAtTimestamp = t.number();
12  
13    creator = t.string();
14  
15    // You can do autoincrements with those!
16    @defaultValue(() => ++i)
17    id = t.number();
18  
19    // If you don't pass in functions, it'll keep the same value forever.
20    @defaultValue("New World")
21    worldName = t.string();
22  }
23  
24  console.log(deserialize(MyModel, {
25    creator: "Vexcited"
26  }));
27  
28  // Let's run a timeout, to check the `@defaultValue(Date.now)`
29  // Could've done the same with `@defaultValue(() => new Date().getTime())`
30  setTimeout(() => {
31    console.log(deserialize(MyModel, {
32      creator: "Vexcited",
33      worldName: "My Awesome World"
34    }));
35  }, 2000);