Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

TypeScript 枚举


枚举 (enum) 是一种特殊的“类”,它表示一组常量(不可更改的变量)。

枚举有两种类型:字符串数字。让我们从数字类型开始。


数字枚举 - 默认值

默认情况下,枚举会将第一个值初始化为 0,并为每个后续值加 1。

示例

enum CardinalDirections {
  North,
  East,
  South,
  West
}
let currentDirection = CardinalDirections.North;
// 输出 0
console.log(currentDirection);
// 抛出错误,因为 'North' 不是有效的枚举值
currentDirection = 'North'; // 错误: "North" 无法赋值给类型 "CardinalDirections"。
自己尝试 »

数字枚举 - 初始化

您可以设置第一个数字枚举的值,并让它从该值开始自动递增。

示例

enum CardinalDirections {
  North = 1,
  East,
  South,
  West
}
// 输出 1
console.log(CardinalDirections.North);
// 输出 4
console.log(CardinalDirections.West);
自己尝试 »

数字枚举 - 完全初始化

您可以为每个枚举值分配唯一数字值。然后这些值将不会自动递增。

示例

enum StatusCodes {
  NotFound = 404,
  Success = 200,
  Accepted = 202,
  BadRequest = 400
}
// 输出 404
console.log(StatusCodes.NotFound);
// 输出 200
console.log(StatusCodes.Success);
自己尝试 »

w3schools CERTIFIED . 2022

获得认证!

完成 TypeScript 模块,进行练习,参加考试并成为 w3schools 认证专家!!

45 美元 报名

字符串枚举

枚举也可以包含 字符串。由于其可读性和意图,这比数字枚举更常见。

示例

enum CardinalDirections {
  North = 'North',
  East = "East",
  South = "South",
  West = "West"
};
// 输出 "North"
console.log(CardinalDirections.North);
// 输出 "West"
console.log(CardinalDirections.West);
自己尝试 »

从技术上讲,您可以混合匹配字符串和数字枚举值,但不建议这样做。


TypeScript 练习

通过练习测试自己

练习

创建一个名为 myEnum 的枚举,其中包含 2 个常量(myFirstConst、mySecondConst),并使用默认值。

enum  {
  ,
  
};
        

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.