How to add a Type to a Class in Javascript?
I'm creating a generic class to work with my other classes. This Class takes a Type of T
public class Heap<T> {
T[] items;
}
I don't know how to write this in Javascript. Its the "public class Heap {" line that throws an error. In javascript I have.
public class Heap {
var items : T[];
}
Anyone have an Idea of what I can do?
Answer by MaxGuernseyIII · Oct 20, 2017 at 09:31 PM
I'm not seeing evidence that you can declare a class with a type parametric in Unity's dialect of JavaScript. You can use them.
There are dozens, perhaps hundreds, of of examples of using a generic class in a JavaScript class. However, I can't find any examples of how you might define one.
Maybe the assumption was that people wanting to use parametric polymorphism would want a big boy language anyway? ;)
I don't know. I would just define the class using C#. If you need it to work in non-Unity JavaScript, use Bridge.NET to generate the JavaScript.
I agree, why would you want generics, a feature that advocates for type safety, in a language that is naturally and essentially type-unsafe like Javascript?
UnityScript is not Javascript(EC$$anonymous$$AScript). It's a proprietary .NET language that has a syntax which has been influenced by JavaScript. Yes it allows to use dynamical typing in exchange for massive a performance drop. However nobody uses UnityScript without "pragma strict". With that pragma UnityScript is as typesafe as C# is. It enforces you to use static typing everywhere just like C#.
However you are right that UnityScript doesn't have a way to declare generics (not that i know). In the beginning it doesn't even has a way to declare properties, however now it's possible.
Just to make that clear: I do not use UnityScript, ever (besides when answering questions here ^^).