/ examples / enum.ts
enum.ts
 1  import { deserialize, deserializeWith, rename, t, u } from "../src";
 2  
 3  /// Values are what the API actually returns.
 4  /// Serde in Rust would've done this like this:
 5  ///
 6  /// #[derive(Serialize, Deserialize)]
 7  /// enum MyEnum {
 8  ///   #[serde(rename = "hello")]
 9  ///   Value1,
10  ///   #[serde(rename = "world")]
11  ///   Value2,
12  /// }
13  ///
14  /// Sadly, we can't have decorators in TS' enums.
15  /// Also, it's not an issue if you use a `@deserializeWith`
16  /// in pair with a `t.enum(MyEnum)` since it does barely nothing.
17  enum MyEnum {
18    Value1 = "hello",
19    Value2 = "world"
20  }
21  
22  class MyModel {
23    @deserializeWith(u.pick("value"))
24    @rename("inner-enum")
25    values = t.array(t.enum(MyEnum));
26  
27    get keys(): string[] {
28      const valueToKey = Object.fromEntries(
29        Object.entries(MyEnum).map(([key, value]) => [value, key])
30      );
31  
32      return this.values.map((value) => valueToKey[value]!);
33    }
34  }
35  
36  const model = deserialize(MyModel, {
37    "inner-enum": [
38      { value: "hello" },
39      { value: "world" }
40    ]
41  });
42  
43  /// The only difference with Rust is that the value logged
44  /// is not the enum key, it's the enum value.
45  console.log(model.values);
46  
47  /// If you want to match the behavior with Rust.
48  console.log(model.keys);