typeshaxe

Haxe doesn’t have the Literal types?


TypeScript and Python (3.8.x and newer) supports Literal types but looks like Haxe doesn’t (for now).

I need to pass a string to the function without typos like in following code.

TypeScript:

type LiteralStatus = "modified" | "corrupted";

class tsFile {
  status: string;
  constructor() {
    this.status = "new";
  }
  set_status(status: LiteralStatus) {
    this.status = status;
  }
  get_status() {
    return this.status;
  }
}

const file = new(tsFile)

console.log(file.get_status()); // new

file.set_status("modified"); // modified
console.log(file.get_status());

// file.set_status("classified") // Throws an exception because argument is not assignable to parameter
// file.set_status() // Throws an exception because the function was expecting for at least one argument

file.set_status("corrupted"); // corrupted
console.log(file.get_status())

Python:

from typing import Literal

class pyFile():
  def __init__(self):
    self.status = "new"

  def set_status(self, status: Literal["modified", "corrupted"]):
    self.status = status
    
  def get_status(self):
    return self.status

file = pyFile()

print(file.get_status()) # new

file.set_status("modified") # modified
print(file.get_status())

# file.set_status("classified") # Throws the TypeError exception
# file.set_status() # Throws the TypeError exception

file.set_status("corrupted") # corrupted
print(file.get_status())

What is the best pattern to create these literal types in Haxe?


Solution

  • You can use enum abstracts

    enum abstract Status(String) from String {
        var Modified = "modified";
        var Corrupted = "corrupted";
    }
    
    
    class File {
        var status:Status = "new";
        
        public function new() {}
        
        public function get_status():Status {
            return status;
        }
        
        public function set_status(status:Status) {
            this.status = status;
        }
    }
    
    function main() {
      final file = new File();
      trace(file.get_status());
    
      file.set_status(Modified);
      trace(file.get_status());
    
      file.set_status(Corrupted);
      trace(file.get_status());
    }
    

    https://try.haxe.org/#95E9203E