@typescript-eslint/no-unsafe-enum-assignment

Disallow giving a plain number or string to a place typed as an enum

needs types

Also called typescript-eslint/no-unsafe-enum-assignment, typescript/no-unsafe-enum-assignment

The compiler accepts a plain number where a numeric enum is expected, and as turns a number or a string into an enum. The code then depends on the raw values behind the members, and the variable can hold a value that no switch over the enum handles.

The rule checks variables, assignments, default values, arguments, return values, class properties, JSX attributes, array and object literal elements, and as assertions. It also reports arithmetic on an enum variable, such as current++, and a plain number or string used as a key of an object with enum keys.

Configure#

Off by default. This rule needs types, so turning it on makes bun lint type check your code first.

bunfig.toml
[lint.rules]
"@typescript-eslint/no-unsafe-enum-assignment" = "error" # or "warn"

Examples#

example.ts6 problems
enum Status {
  Open,
  Closed,
}

declare function setStatus(next: Status): void;
declare const labels: { [key in Status]: string };

let current: Status = 1;
current++;
setStatus(0);
console.log(labels[0]);
const parsed = Number("1") as Status;
const all: Status[] = [Status.Open, 1];
example.tsNo problems
enum Status {
  Open,
  Closed,
}

declare function setStatus(next: Status): void;
declare const labels: { [key in Status]: string };

let current: Status = Status.Closed;
current = Status.Open;
setStatus(Status.Open);
console.log(labels[Status.Open]);
const all: Status[] = [Status.Open, Status.Closed];

// This type accepts any number, so a plain number is fine.
const code: Status | number = 404;

Combining members of the same enum with |, &, ^ and ~ is allowed, because that's how flag enums work:

example.tsNo problems
enum Access {
  Read = 1,
  Write = 2,
}

let access: Access = Access.Read | Access.Write;
access &= ~Access.Write;

When not to use it#

Values from outside, such as JSON or a database, arrive as plain numbers and strings. If you turn them into enums with as in many places, this rule reports each one. If you convert them in one checked function, only that function is reported.