oxc-project/oxc · error · OxcDiagnostic

Expected a `const` assertion instead of a literal type annot

Error message

Expected a `const` assertion instead of a literal type annotation.

What it means

Raised by typescript/prefer_as_const when a variable or property is annotated with a literal type (e.g. `let x: 2 = 2;` or `x: 'a' = 'a'`) instead of using a `const` assertion (`x = 2 as const`). At the throw site the annotation pins the type to the literal while duplicating the value, and `as const` expresses the same intent more idiomatically while also working where annotations don't (deep object/array literals). prefer_as_const_diagnostic fires from check_and_report_as_expression and check_and_report_type_annotation for literal-type annotations whose initializer matches.

Source

Thrown at crates/oxc_linter/src/rules/typescript/prefer_as_const.rs:16

use oxc_ast::{
    AstKind,
    ast::{BindingPattern, Expression, TSLiteral, TSType, TSTypeAnnotation},
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{
    AstNode,
    context::{ContextHost, LintContext},
    rule::Rule,
};

fn prefer_as_const_diagnostic(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Expected a `const` assertion instead of a literal type annotation.")
        .with_help("You should use `as const` instead of type annotation.")
        .with_label(span)
}

#[derive(Debug, Default, Clone)]
pub struct PreferAsConst;

declare_oxc_lint!(
    /// ### What it does
    ///
    /// Enforce the use of `as const` over literal types.
    ///
    /// ### Why is this bad?
    ///
    /// 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 automatically

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Use `as const`: let x = "foo" as const.
  2. Remove the redundant literal type annotation where possible.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/typescript/prefer_as_const.rs:16 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/789ad6982d5524cd. Report an issue: GitHub.