TypeScriptのEnum
2020.2 https://www.kabuku.co.jp/developers/good-bye-typescript-enum
union型を使うほうがわかりやすいという主張
const assertionを使うとリテラル型になる
code:ts
const foo: Foo = "foo" as const;
type Foo = typeof foo; // fooのみを設定できるリテラル型
const foo2: Foo = "bar"; // foo以外を設定したらエラー
https://www.cyokodog.net/blog/typescript-enum-replacement/
2020.7 https://engineering.linecorp.com/ja/blog/typescript-enum-tree-shaking/
valueOfの実装
(string) => enum
TypeScript EnumにvalueOfメソッドを実装する - Qiita
stringのEnum
code:ts
enum Foo {
BAR = 'bar'
}
console.log(Foo'foo') // undefined
console.log(Foo'BAR') // bar
console.log(Foo'bar') // undefined
code:ts
enum Foo {
BAR = 'bar'
}
// enumに対してkeyofすると予想と違う結果になる
const keyStr = params.get(key) as keyof Foo
return FookeyStr;
// Element implicitly has an 'any' type because expression of type 'number | unique symbol | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | ... 34 more ... | "replaceAll"' can't be used to index type 'typeof Foo'
// 正しく動かすにはこう
const keyStr = params.get(key) as keyof typeof Foo
return FookeyStr;
なんでこうなるの?
関連 typeofとkeyofとinの複合