3

I've used JSWEET to transpile a large Java project. It has converted types like Enumeration<Object> directly to Enumeration<any> in TypeScript.

In the Java world it was possible to assign an array Object[] to an Enumeration<Object>.

In Typescript I get: Type 'any[]' is not assignable to type 'Enumeration<any>'

Is there a way to extend Enumeration<Object> OR any[] in such a way that TypeScript will allow this assignment to occur?

Mark Rabjohn
  • 1,643
  • 14
  • 30
  • 1
    Java doesn't allow you to assign an `Object[]` to an `Enumeration` but never the less I assume you don't need the answer about Java so removing the tag. – Peter Lawrey Oct 04 '16 at 12:03
  • Could you tell more about what you mean by "In the Java world it was possible to assign an array Object[] to an Enumeration"? If you actually try to write `Enumeration e = anArray;` in Java, you get a type mismatch error. So what is your context here? – Renaud Pawlak Oct 05 '16 at 10:55
  • I'm generating Typescript from Java, but I made a mistake in some of my additional parts which led to my presumption that you could assign those two types in Java. Doesn't look like C++/C# style cast operators can be written in Typescript though. – Mark Rabjohn Oct 10 '16 at 15:31

1 Answers1

0

You can cast in two different ways:

var doSomething = function <T>(a: Enumeration<T>) { };
var x: Object[] = [];

// cast using "<>""
doSomething(<Enumeration<Object>>x);

// cast using "as"
doSomething(x as Enumeration<Object>);

But your Enumeration should probably extend Array:

interface Enumeration<T> extends Array<T> {
    // ...
}

Update

class Enumeration<T> extends Array<T> {
    private _cursor: number;
    public constructor(...elements: T[]) {
        super(...elements);
        this._cursor = 0;
    }
    public nextElement() {
        this._cursor = this._cursor + 1;
        return this.values[this._cursor];
    };
    public hasMoreElements() {
        return this._cursor < this.length - 1;
    }
    public static fromArray<T>(arr: T[]) {
        return new Enumeration<T>(...arr);
    }
}

interface User {
    name: string;
}

let a: Array<User> = [{ name: "user1" }, { name: "user2" }];
let b: Enumeration<User> = new Enumeration({ name: "user1" }, { name: "user2" });

a = b; // OK: Enumeration<User> is assignable to Array<User>
b = a; // Error: Array<User> is not assignable to Enumeration<User>

Maybe you can add a method fromArray to the enumeration class:

var doSomething = function <T>(a: Enumeration<T>) { };
doSomething(Enumeration.fromArray<User>(a));
Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93