prefer-as-const
Enforce the use of
as const
over literal type.
✅
Extending "plugin:@typescript-eslint/recommended"
in an ESLint configuration enables this rule.
🔧
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
💡
Some problems reported by this rule are manually fixable by editor suggestions.
There are two common ways to tell TypeScript that a literal value should be interpreted as its literal type (e.g. 2
) rather than general primitive type (e.g. number
);
as const
: telling TypeScript to infer the literal type automaticallyas
with the literal type: explicitly telling the literal type to TypeScript
as const
is generally preferred, as it doesn't require re-typing the literal value.
This rule reports when an as
with an explicit literal type can be replaced with an as const
.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-as-const": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
let bar: 2 = 2;
let foo = <'bar'>'bar';
let foo = { bar: 'baz' as 'baz' };
Open in Playgroundlet foo = 'bar';
let foo = 'bar' as const;
let foo: 'bar' = 'bar' as const;
let bar = 'bar' as string;
let foo = <string>'bar';
let foo = { bar: 'baz' };
Open in PlaygroundOptions
This rule is not configurable.
When Not To Use It
If you are using TypeScript < 3.4