How to check the type of a vector element

I would like to execute a function depending of the variable type. How can I do that?

For instance, it should be somethin like that:

let textVec = ["1", "2", "3", "1", "2", "3", "1"];
let aux = textVec[0];
switch (aux) {
  case (Text) {
    Debug.print("is a text:" # aux);


1 Like

I’m assuming this is a Motoko question.

I recommend creating a variant type that expresses the type you are storing in your array, and tagging the entry as a variant. This would look like this:

  type TextOrNat = {
    #text: Text;
    #nat: Nat

  var list: [TextOrNat] = [#text "some text", #nat 0, #text "0"];

Here’s an example: Motoko Playground - DFINITY

I’ve written up a simple explainer here: Using Motoko Variants


Reflection in motoko has been an often requested feature. There are apparently issues with implementing it:

If you absolutely must have it, you may have some success with GitHub - edjCase/motoko_candid. You need to to_candid your object into a candid format and then parse through the resultant object.

This would be useful if you were trying to read the memory store of a canister that just dumped state to a blob array and that contained unknown types and you were trying to marshal them to known types.

1 Like