TypeScriptのEnum
union型を使うほうがわかりやすいという主張
code:ts
const foo: Foo = "foo" as const;
type Foo = typeof foo; // fooのみを設定できるリテラル型
const foo2: Foo = "bar"; // foo以外を設定したらエラー
valueOfの実装
(string) => enum
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
// 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
なんでこうなるの?