Back to Biomejs

useLiteralEnumMembers

src/content/docs/linter/rules/use-literal-enum-members.mdx

latest3.0 KB
Original Source

import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs> <TabItem label="TypeScript and TSX" icon="seti:typescript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/style/useLiteralEnumMembers`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule doesn't have a fix. - The default severity of this rule is [**warning**](/reference/diagnostics#warning). - Sources: - Same as [`@typescript-eslint/prefer-literal-enum-member`](https://typescript-eslint.io/rules/prefer-literal-enum-member)

How to configure

json
{
	"linter": {
		"rules": {
			"style": {
				"useLiteralEnumMembers": "error"
			}
		}
	}
}

Description

Require all enum members to be literal values.

Usually, an enum member is initialized with a literal number or a literal string. However, TypeScript allows the value of an enum member to be many different kinds of expressions. Using a computed enum member is often error-prone and confusing. This rule requires the initialization of enum members with constant expressions. It allows numeric and bitwise expressions for supporting enum flags. It also allows referencing previous enum members.

Examples

Invalid

ts
const x = 2;
enum Computed {
    A,
    B = x,
}
<pre class="language-text"><code class="language-text">code-block.ts:4:9 <a href="https://biomejs.dev/linter/rules/use-literal-enum-members">lint/style/useLiteralEnumMembers</a> ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ <strong><span style="color: Orange;">⚠</span></strong> <span style="color: Orange;">The enum member should be initialized with a literal value such as a number or a string.</span> <strong>2 │ </strong>enum Computed &#123; <strong>3 │ </strong> A, <strong><span style="color: Tomato;">&gt;</span></strong> <strong>4 │ </strong> B = x, <strong> │ </strong> <strong><span style="color: Tomato;">^</span></strong> <strong>5 │ </strong>&#125; <strong>6 │ </strong> </code></pre>

Valid

ts
enum Direction {
    Left,
    Right,
}
ts
enum Order {
    Less = -1,
    Equal = 0,
    Greater = 1,
}
ts
enum State {
    Open = "Open",
    Close = "Close",
}
ts
enum FileAccess {
    None = 0,
    Read = 1,
    Write = 1 << 1,
    All = Read | Write
}
</TabItem> </Tabs>