Skip to content
CCPEDIAby Unity Nodes
App Development

How can I create a variant value using the generated TypeScript code?

2 posts243 viewsLast activity Apr 2023

  1. gyorgybalazsiOP

    This is the Daml declaration of a variant type:

    data BookAttribute = Pages Int
                       | Authors [Text]
                       | Title Text
                       | Published with year: Int; publisher: Text
      deriving(Eq, Show)
    

    This is the generated code for BookAttibute:

    exports.BookAttribute = {
      decoder: damlTypes.lazyMemo(function () { return jtv.oneOf(jtv.object({tag: jtv.constant('Pages'), value: damlTypes.Int.decoder, }), jtv.object({tag: jtv.constant('Authors'), value: damlTypes.List(damlTypes.Text).decoder, }), jtv.object({tag: jtv.constant('Title'), value: damlTypes.Text.decoder, }), jtv.object({tag: jtv.constant('Published'), value: exports.BookAttribute.Published.decoder, })); }),
      encode: function (__typed__) {
      switch(__typed__.tag) {
        case 'Pages': return {tag: __typed__.tag, value: damlTypes.Int.encode(__typed__.value)};
        case 'Authors': return {tag: __typed__.tag, value: damlTypes.List(damlTypes.Text).encode(__typed__.value)};
        case 'Title': return {tag: __typed__.tag, value: damlTypes.Text.encode(__typed__.value)};
        case 'Published': return {tag: __typed__.tag, value: exports.BookAttribute.Published.encode(__typed__.value)};
        default: throw 'unrecognized type tag: ' + __typed__.tag + ' while serializing a value of type BookAttribute';
      }
    }
    ,
      Published:({
        decoder: damlTypes.lazyMemo(function () { return jtv.object({year: damlTypes.Int.decoder, publisher: damlTypes.Text.decoder, }); }),
        encode: function (__typed__) {
      return {
        year: damlTypes.Int.encode(__typed__.year),
        publisher: damlTypes.Text.encode(__typed__.publisher),
      };
    }
    ,
      }),
    };
    

    How can I express in the TypeScript code the equivalents of the following Daml values?

    pages: BookAttribute = Pages 100
    authors: BookAttribute = Authors ["Leo Tolstoy", "George Orwell"]
    title: BookAttribute = Title "Alice's Adventures is Wonderland"
    published: BookAttribute = Published 1865 "Macmillan"
    
  2. gyorgybalazsi

    Answering my own question:

    TypeScript doesn’t have constructors, it just offers type annotations for objects, so this is how we can express one of the values above:

    let published : BookAttribute = {"tag": "Published","value":{"year":"1865", "publisher":"Macmillan"}};