TypeScript 和 Python(3.8.x 及更高版本)支持文字类型,但看起来 Haxe 不\xe2\x80\x99t(目前)。
\n我需要将一个字符串传递给函数,而不需要像下面的代码那样出现拼写错误。
\n打字稿:
\ntype LiteralStatus = "modified" | "corrupted";\n\nclass tsFile {\n status: string;\n constructor() {\n this.status = "new";\n }\n set_status(status: LiteralStatus) {\n this.status = status;\n }\n get_status() {\n return this.status;\n }\n}\n\nconst file = new(tsFile)\n\nconsole.log(file.get_status()); // new\n\nfile.set_status("modified"); // modified\nconsole.log(file.get_status());\n\n// file.set_status("classified") // Throws an exception because argument is not assignable to parameter\n// file.set_status() // Throws an exception because the function was expecting for at least one argument\n\nfile.set_status("corrupted"); // corrupted\nconsole.log(file.get_status())\nRun Code Online (Sandbox Code Playgroud)\nPython:
\nfrom typing import Literal\n\nclass pyFile():\n def __init__(self):\n self.status = "new"\n\n def set_status(self, status: Literal["modified", "corrupted"]):\n self.status = status\n \n def get_status(self):\n return self.status\n\nfile = pyFile()\n\nprint(file.get_status()) # new\n\nfile.set_status("modified") # modified\nprint(file.get_status())\n\n# file.set_status("classified") # Throws the TypeError exception\n# file.set_status() # Throws the TypeError exception\n\nfile.set_status("corrupted") # corrupted\nprint(file.get_status())\nRun Code Online (Sandbox Code Playgroud)\n在 Haxe 中创建这些文字类型的最佳模式是什么?
\n您可以使用枚举摘要
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());
}
Run Code Online (Sandbox Code Playgroud)
https://try.haxe.org/#95E9203E