Hi everyone,
I am looking for a way to constrain a String type to a specific set of strings. In Typescript I make liberal use of string literal types which allow something like this:
type Orientation = "portrait" | "landscapeLeft" | "landscapeRight"
and no other strings would be allowed.
Is that (or something similar) possible in Haxe as well? I find that quite useful for externs to dynamic languages that often use a set of strings to denote distinct categories.
enum abstract Orientation(String) {
var portrait;
var landscapeLeft;
var landscapeRight;
}
class Main {
static function draw(orientation:Orientation) {
trace(orientation);
}
static function main() {
draw(portrait);
}
}
generated JS:
class Main {
static draw(orientation) {
console.log("src/Main.hx:9:",orientation);
}
static main() {
Main.draw("portrait");
}
}
Personally I would rather be explicit about the values of the enum abstract fields, so you can use a proper enum value naming convention (both PascalCase and UPPER_CASE are common in Haxe, but lowerCamelCase looks really strange to me).
enum abstract Orientation(String) {
var Portrait = "portrait";
var LandscapeLeft = "landscapeLeft ";
var LandscapeRight = "landscapeLeft";
}
It would be still nice to have this for Haxe too. You can also define them inline in typescript for example, which is not possible with an enum:
function setOrientation(orientation: "portrait" | "landscape") {
console.log(orientation);
}
setOrientation("tilted");
// Argument of type '"test"' is not assignable to parameter of type '"portrait" | "landscape"
I cannot agree. It surely looks cute and is useful in the context of TypeScript, because the idea is to add type-safety for JavaScript with its stringly-typing approaches while staying as close to JavaScript syntax as possible (so you can mostly just copy-paste code between languages). But in any other situation IMO this is just gimmicky.
(Since I use this feature a lot in TS, I am biased toward making it available in Haxe as well - it may be gimmicky, but it is also very easy to understand and I like the ergonomics of it, it feels lightweight. Anyway, since I can get what I need with abstract enums, I am happy nonetheless)