prefer_const

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var PreferConstRule = rule.Rule{
	Name: "prefer-const",
	Run: func(ctx rule.RuleContext, options any) rule.RuleListeners {
		if ctx.TypeChecker == nil {
			return rule.RuleListeners{}
		}

		opts := parseOptions(options)

		return rule.RuleListeners{
			ast.KindVariableDeclarationList: func(node *ast.Node) {
				declList := node.AsVariableDeclarationList()
				if declList == nil || node.Flags&ast.NodeFlagsLet == 0 || declList.Declarations == nil {
					return
				}

				if isInForStatement(node) {
					return
				}

				isForInOrOf := isInForInOrOf(node)

				for _, decl := range declList.Declarations.Nodes {
					varDecl := decl.AsVariableDeclaration()
					if varDecl == nil || varDecl.Name() == nil {
						continue
					}

					hasInit := varDecl.Initializer != nil || isForInOrOf

					candidates := collectBindingNames(varDecl.Name(), hasInit)
					if len(candidates) == 0 {
						continue
					}

					// Check each candidate
					var constCandidates []*candidateInfo
					for i := range candidates {
						c := &candidates[i]
						if shouldReport(c, decl, &ctx, opts) {
							constCandidates = append(constCandidates, c)
						}
					}

					isDestructuring := varDecl.Name().Kind == ast.KindObjectBindingPattern ||
						varDecl.Name().Kind == ast.KindArrayBindingPattern
					if isDestructuring && opts.destructuring == "all" {

						if len(constCandidates) != len(candidates) {
							continue
						}
					}

					for _, c := range constCandidates {
						name := c.nameNode.Text()
						reportOn := c.nameNode
						if c.reportNode != nil {
							reportOn = c.reportNode
						}
						ctx.ReportNode(reportOn, rule.RuleMessage{
							Id:          "useConst",
							Description: "'" + name + "' is never reassigned. Use 'const' instead.",
						})
					}
				}
			},
		}
	},
}

https://eslint.org/docs/latest/rules/prefer-const

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL