cadl/docs/language-basics/enums.md

81 строка
1.6 KiB
Markdown
Исходник Постоянная ссылка Обычный вид История

2022-09-06 19:46:31 +03:00
---
id: enums
title: Enums
---
# Enums
Enums, short for enumerations, provide a way for developers to define a collection of named constants. They are useful for documenting the purpose of the code or for establishing a set of distinct scenarios. Enums can be either numeric or string-based. For other data types, consider using [unions](./unions.md).
2022-09-06 19:46:31 +03:00
## The basics
2022-09-06 19:46:31 +03:00
You can declare enums using the `enum` keyword. The members of an enum are separated by commas `,` and can be either `identifier` TypeSpecs or `string literal`s.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
enum Direction {
North,
East,
South,
West,
}
```
In the above example, we haven't defined the representation of the constants. Depending on the context, enums might be handled differently.
2022-09-06 19:46:31 +03:00
## Assigning values to enums
2022-09-06 19:46:31 +03:00
You can assign custom values to enum members using the `:` operator.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
enum Direction {
North: "north",
East: "east",
South: "south",
West: "west",
}
```
These values can also be integers.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
enum Foo {
One: 1,
Ten: 10,
Hundred: 100,
Thousand: 1000,
}
```
Or even floating-point numbers.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
enum Hour {
Zero: 0,
Quarter: 0.25,
Half: 0.5,
ThreeQuarter: 0.75,
2022-09-06 19:46:31 +03:00
}
```
## Combining enums
2022-09-06 19:46:31 +03:00
You can combine enums using the spread `...` pattern. This copies all the members from the source enum to the target enum, but it doesn't establish any reference between the source and target enums.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
enum DirectionExt {
...Direction,
`North East`,
`North West`,
`South East`,
`South West`,
2022-09-06 19:46:31 +03:00
}
```
## How to reference enum members
2022-09-06 19:46:31 +03:00
You can reference enum members using the `.` operator for identifiers.
2022-09-06 19:46:31 +03:00
2023-02-16 01:37:39 +03:00
```typespec
2022-09-06 19:46:31 +03:00
alias North = Direction.North;
```