Back to Type Challenges

README.Zh CN

questions/00472-hard-tuple-to-enum-object/README.zh-CN.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/zh-CN" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> <a href="./README.ja.md" target="_blank"></a> </p><!--info-header-end-->

枚举是 TypeScript 的一种原生语法(在 JavaScript 中不存在)。因此在 JavaScript 中枚举会被转成如下形式的代码:

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

在这个问题中,你实现的类型应当将给定的字符串元组转成一个行为类似枚举的对象。此外,枚举的属性一般是 pascal-case 的。

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

如果传递了第二个泛型参数,且值为 true,那么返回值应当是一个 number 字面量。

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

<a href="../../README.zh-CN.md" target="_blank"></a> <a href="https://tsch.js.org/472/answer/zh-CN" 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.zh-CN.md" target="_blank"></a> <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.zh-CN.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-->