Assemblyscript: Is it possible to call a static function on generic type <T>?

Created on 15 Mar 2019  ·  3Comments  ·  Source: AssemblyScript/assemblyscript

Example:

class Temp {
  static decode(buf: Uint8Array): Temp {
    return new Temp(); 
  }
}

function decode<T>(buf: Uint8Array): T {
  return T.decode(buf);
}

let a = decode<Temp>(new Uint8Array());
question

Most helpful comment

No, this also not possible in typescript.
But you could do something like this:

class Base {
  static decode<T>(buf: Uint8Array): T {
    return instantiate<T>(); // `instantiate` is AssemblyScript's builtin
  }
}

class Temp extends Base {
}

let a = Base.decode<Temp>(new Uint8Array(1));

All 3 comments

No, this also not possible in typescript.
But you could do something like this:

class Base {
  static decode<T>(buf: Uint8Array): T {
    return instantiate<T>(); // `instantiate` is AssemblyScript's builtin
  }
}

class Temp extends Base {
}

let a = Base.decode<Temp>(new Uint8Array(1));

If you know the output is a reference, you can use the changetype macro like this.

changetype<T>(changetype<usize>(T.decode(buf)));

You will be responsible for making sure the output of the decode function matches the definition of the T data type.

This is not safe, and you would need to know what you are doing.

Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

torch2424 picture torch2424  ·  5Comments

Iainmon picture Iainmon  ·  3Comments

DanielMazurkiewicz picture DanielMazurkiewicz  ·  4Comments

kungfooman picture kungfooman  ·  5Comments

solidsnail picture solidsnail  ·  5Comments