Back to Type Challenges

README.Ja

questions/00472-hard-tuple-to-enum-object/README.ja.md

latest3.5 KB
Original Source
<!--info-header-start--><h1>Tuple to Enum Object </h1><blockquote><p>by Ryo Hanafusa <a href="https://github.com/softoika" target="_blank">@softoika</a></p></blockquote><p><a href="https://tsch.js.org/472/play/ja" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> <a href="./README.zh-CN.md" target="_blank"></a> </p><!--info-header-end-->

enum は TypeScript 独自の文法です(JavaScript にはありません)。そのため、以下の形式にトランスパイルされます。

js
let OperatingSystem
;(function (OperatingSystem) {
  OperatingSystem[(OperatingSystem['MacOS'] = 0)] = 'MacOS'
  OperatingSystem[(OperatingSystem['Windows'] = 1)] = 'Windows'
  OperatingSystem[(OperatingSystem['Linux'] = 2)] = 'Linux'
})(OperatingSystem || (OperatingSystem = {}))

この問題では、文字列のタプルを enum と同じようなオブジェクトに変換する型を実装します。 さらに、enum のプロパティはパスカルケースであることが好ましいです。

ts
Enum<['macOS', 'Windows', 'Linux']>
// -> { readonly MacOS: "macOS", readonly Windows: "Windows", readonly Linux: "Linux" }

第 2 引数にtrueが与えられた場合、値は数値リテラルとなります。

ts
Enum<['macOS', 'Windows', 'Linux'], true>
// -> { readonly MacOS: 0, readonly Windows: 1, readonly Linux: 2 }
<!--info-footer-start-->

<a href="../../README.ja.md" target="_blank"></a> <a href="https://tsch.js.org/472/answer/ja" target="_blank"></a> <a href="https://tsch.js.org/472/solutions" target="_blank"></a> <hr><h3>関連する課題</h3><a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00010-medium-tuple-to-union/README.ja.md" target="_blank"></a> <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.ja.md" target="_blank"></a> <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00730-hard-union-to-tuple/README.md" target="_blank"></a> <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/03188-medium-tuple-to-nested-object/README.md" target="_blank"></a> <!--info-footer-end-->