enumよりstring literalを使ったほうがいい
(※個人の感想です)
code:string-literal.ts
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
if (easing === "ease-in") {
// ...
}
else if (easing === "ease-out") {
}
else if (easing === "ease-in-out") {
}
else {
// error! should not pass null or undefined.
}
}
}
let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy"); // error: "uneasy" is not allowed here
swagger-codegenで string-enums and string-unions について議論されているIssueがあった(ちょっとString literalを使いたい動機が違うっぽいけど)
使いたい側のコードに対して値を透明にしておきたい場合はstring-unions
使いたい側のコードに対して値を不透明にしておきたい(変更されるかもしれない)場合はstring-enums
ということっぽい?
挙動的には、string-unionだと型の検証にしか影響を与えないけど、Enumだとコンパイル後のコードに影響を与えるようになっているらしい。
調べていたら
string literal
enum
const enum
あたりに少し詳しくなった。
同じようなことを考えている人をちょこちょこ観測している