CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-typescript-eslint--utils

Utilities for working with TypeScript + ESLint together

Pending
Overview
Eval results
Files

index.mddocs/

@typescript-eslint/utils

Comprehensive utilities for working with TypeScript and ESLint together. This package provides a complete toolkit for developing ESLint rules with TypeScript support, including AST manipulation utilities, rule creation helpers, JSON Schema types, and TypeScript-specific utilities.

Package Information

  • Package Name: @typescript-eslint/utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @typescript-eslint/utils

Core Imports

// Main namespace imports
import { ASTUtils, ESLintUtils, JSONSchema, TSESLint, TSUtils } from '@typescript-eslint/utils';

// Individual namespace imports
import { ASTUtils } from '@typescript-eslint/utils';
import { ESLintUtils } from '@typescript-eslint/utils';
import { JSONSchema } from '@typescript-eslint/utils';
import { TSESLint } from '@typescript-eslint/utils';
import { TSUtils } from '@typescript-eslint/utils';

// Re-exported types from dependencies
import { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree } from '@typescript-eslint/utils';
import type { ParserServices, ParserServicesWithTypeInformation } from '@typescript-eslint/utils';

Alternative subpath imports:

// Import from specific subpaths (as defined in package.json exports)
import * as ASTUtils from '@typescript-eslint/utils/ast-utils';
import * as ESLintUtils from '@typescript-eslint/utils/eslint-utils';
import * as JSONSchema from '@typescript-eslint/utils/json-schema';
import * as TSESLint from '@typescript-eslint/utils/ts-eslint';

Basic Usage

Creating an ESLint Rule

import { ESLintUtils } from '@typescript-eslint/utils';

// Create a rule creator with documentation URL generator
const createRule = ESLintUtils.RuleCreator(
  name => `https://example.com/rules/${name}`
);

// Define and export a rule
export default createRule({
  name: 'my-custom-rule',
  meta: {
    type: 'problem',
    docs: {
      description: 'My custom TypeScript ESLint rule',
    },
    messages: {
      error: 'This is not allowed: {{details}}',
    },
    schema: [
      {
        type: 'object',
        properties: {
          checkStrings: { type: 'boolean' }
        },
        additionalProperties: false,
      }
    ],
  },
  defaultOptions: [{ checkStrings: true }],
  create(context) {
    return {
      CallExpression(node) {
        context.report({
          node,
          messageId: 'error',
          data: { details: 'function calls' }
        });
      }
    };
  },
});

Using AST Utilities

import { ASTUtils } from '@typescript-eslint/utils';

// In a rule implementation
create(context) {
  return {
    CallExpression(node) {
      // Check for optional call expressions
      if (ASTUtils.isOptionalCallExpression(node)) {
        // Handle optional chaining calls like obj?.method()
      }
      
      // Check if node is a function
      if (ASTUtils.isFunction(node.callee)) {
        // Handle direct function calls
      }
    },
    
    MemberExpression(node) {
      // Check for type assertions
      if (ASTUtils.isTypeAssertion(node.object)) {
        // Handle type assertions like (obj as Type).prop
      }
    }
  };
}

Accessing Type Information

import { ESLintUtils } from '@typescript-eslint/utils';

// In a rule that needs type information
create(context) {
  // Get parser services for type-aware linting
  const services = ESLintUtils.getParserServices(context);
  const checker = services.program.getTypeChecker();
  
  return {
    Identifier(node) {
      // Convert ESTree node to TypeScript node
      const tsNode = services.esTreeNodeToTSNodeMap.get(node);
      
      // Get type information
      const type = checker.getTypeAtLocation(tsNode);
      const typeString = checker.typeToString(type);
      
      if (typeString === 'string') {
        // Handle string types specifically
      }
    }
  };
}

Architecture Overview

The package is organized into five main namespaces, each serving specific aspects of TypeScript ESLint development:

ASTUtils Namespace

Provides comprehensive utilities for Abstract Syntax Tree manipulation and analysis:

  • Node type predicates: Check for specific AST node types (functions, identifiers, expressions)
  • Token predicates: Validate token types (punctuators, keywords, operators)
  • Helper functions: Node type guards and conditional type checking
  • ESLint utilities: Integration helpers for ESLint-specific AST operations

ESLintUtils Namespace

Contains rule creation and ESLint integration utilities:

  • Rule creation: RuleCreator for generating well-documented rules
  • Parser services: Access TypeScript compiler API within rules
  • Option handling: Default option application and deep merging
  • Type inference: Extract types from rule definitions

JSONSchema Namespace

Provides complete JSON Schema v4 types for rule configuration:

  • Schema types: All JSON Schema primitive and complex types
  • Validation schemas: Object, array, string, number schema definitions
  • Composition schemas: AllOf, AnyOf, OneOf schema combinations
  • Reference handling: Schema references and reusable definitions

TSESLint Namespace

Offers TypeScript-enhanced ESLint types and classes:

  • Configuration: Both legacy and flat config types
  • Rules: Enhanced rule interfaces with TypeScript support
  • Linting: ESLint and Linter classes with TypeScript integration
  • Scope analysis: Variable and reference tracking
  • Source code: Enhanced source code representation

TSUtils Namespace

Provides TypeScript-specific utility functions:

  • Type guards: Runtime type checking utilities
  • Type manipulation: Utility types for TypeScript development
  • Array handling: Type-safe array operations

Key Capabilities

Rule Development

Create sophisticated ESLint rules with full TypeScript support:

import { ESLintUtils, ASTUtils, TSESLint } from '@typescript-eslint/utils';

const createRule = ESLintUtils.RuleCreator(name => `https://docs.example.com/${name}`);

type Options = [{
  allowOptional?: boolean;
  ignoreArrays?: boolean;
}];

type MessageIds = 'noUnsafeCall' | 'preferOptional';

export default createRule<Options, MessageIds>({
  name: 'safe-member-access',
  meta: {
    type: 'problem',
    docs: {
      description: 'Enforce safe member access patterns',
    },
    messages: {
      noUnsafeCall: 'Unsafe member access detected',
      preferOptional: 'Consider using optional chaining: {{suggestion}}'
    },
    schema: [{
      type: 'object',
      properties: {
        allowOptional: { type: 'boolean' },
        ignoreArrays: { type: 'boolean' }
      },
      additionalProperties: false
    }]
  },
  defaultOptions: [{ allowOptional: true, ignoreArrays: false }],
  create(context, [options]) {
    const services = ESLintUtils.getParserServices(context);
    
    return {
      MemberExpression(node) {
        // Use type information and AST utilities together
        if (!options.allowOptional && ASTUtils.isOptionalCallExpression(node)) {
          context.report({
            node,
            messageId: 'preferOptional',
            data: { suggestion: 'obj?.method()' }
          });
        }
      }
    };
  }
});

→ See complete ESLint utilities documentation

AST Analysis and Manipulation

Comprehensive AST utilities for analyzing TypeScript code structures:

import { ASTUtils, TSESTree } from '@typescript-eslint/utils';

// Node type checking
const isFunction = ASTUtils.isFunction(node);
const isOptionalCall = ASTUtils.isOptionalCallExpression(node);
const isTypeAssertion = ASTUtils.isTypeAssertion(node);

// Token analysis
const isArrow = ASTUtils.isArrowToken(token);
const isComma = ASTUtils.isCommaToken(token);
const isSemicolon = ASTUtils.isSemicolonToken(token);

// Advanced type checking with conditions
const isSpecificFunction = ASTUtils.isNodeOfTypeWithConditions(
  AST_NODE_TYPES.FunctionDeclaration,
  { async: true }
);

→ See complete AST utilities documentation

Type-Safe Configuration

Define rule schemas with complete type safety using JSON Schema:

import { JSONSchema } from '@typescript-eslint/utils';

// Complete rule schema definition
const ruleSchema: JSONSchema.JSONSchema4 = {
  type: 'object',
  properties: {
    mode: {
      type: 'string',
      enum: ['strict', 'loose', 'disabled']
    },
    exceptions: {
      type: 'array',
      items: { type: 'string' },
      minItems: 0
    },
    config: {
      type: 'object',
      properties: {
        checkReturnTypes: { type: 'boolean' },
        allowAny: { type: 'boolean' }
      },
      additionalProperties: false
    }
  },
  additionalProperties: false,
  required: ['mode']
};

→ See complete JSON Schema documentation

Enhanced ESLint Integration

Access all ESLint functionality with TypeScript enhancements:

import { TSESLint } from '@typescript-eslint/utils';

// Type-aware rule context
function createRule(context: TSESLint.RuleContext<MessageIds, Options>) {
  // Enhanced source code access
  const sourceCode = context.getSourceCode();
  const tokens = sourceCode.getTokens(node);
  
  // Scope analysis
  const scope = context.getScope();
  const variables = scope.variables;
  
  // Type-safe reporting
  context.report({
    node,
    messageId: 'error' as const,
    data: { name: 'example' },
    fix: (fixer) => fixer.replaceText(node, 'replacement')
  });
}

→ See complete TSESLint documentation

TypeScript Utilities

Additional TypeScript-specific utilities for enhanced development:

import { TSUtils } from '@typescript-eslint/utils';

// Type-safe array checking
if (TSUtils.isArray(value)) {
  // value is now typed as readonly unknown[]
  value.forEach(item => {
    // Safe array iteration
  });
}

// Prevent type inference when needed
function example<T>(value: TSUtils.NoInfer<T>) {
  // T will not be inferred from value parameter
}

→ See complete TypeScript utilities documentation

AST Types and Parser Services

Re-exported core TypeScript AST types and parser services for convenient access:

// AST Node types enumeration
import { AST_NODE_TYPES } from '@typescript-eslint/utils';

// AST Token types enumeration  
import { AST_TOKEN_TYPES } from '@typescript-eslint/utils';

// TypeScript ESTree types
import { TSESTree } from '@typescript-eslint/utils';

// Parser service types for TypeScript integration
import type { 
  ParserServices,
  ParserServicesWithTypeInformation,
  ParserServicesWithoutTypeInformation 
} from '@typescript-eslint/utils';

These are convenience re-exports from @typescript-eslint/types and @typescript-eslint/typescript-estree packages, eliminating the need to install and import from multiple packages.

Usage Example:

import { AST_NODE_TYPES, TSESTree, ESLintUtils } from '@typescript-eslint/utils';

const createRule = ESLintUtils.RuleCreator(name => `https://example.com/${name}`);

export default createRule({
  name: 'example-rule',
  meta: {
    type: 'problem',
    docs: { description: 'Example rule using AST types' },
    messages: { error: 'Error found in {{nodeType}}' },
    schema: []
  },
  defaultOptions: [],
  create(context) {
    return {
      [AST_NODE_TYPES.CallExpression](node: TSESTree.CallExpression) {
        context.report({
          node,
          messageId: 'error',
          data: { nodeType: node.type }
        });
      }
    };
  }
});

Documentation Structure

This Knowledge Tile is organized into focused documents covering each major functional area:

  • AST Utilities - Node predicates, token analysis, and AST manipulation helpers
  • ESLint Utilities - Rule creation, parser services, and ESLint integration
  • JSON Schema - Complete JSON Schema v4 types for rule configuration
  • TSESLint Types - TypeScript-enhanced ESLint classes and interfaces
  • TypeScript Utils - TypeScript-specific utility functions and types

Each document provides comprehensive API coverage with practical examples, enabling effective TypeScript ESLint rule development without requiring access to source code.

Install with Tessl CLI

npx tessl i tessl/npm-typescript-eslint--utils

docs

ast-utils.md

eslint-utils.md

index.md

json-schema.md

ts-eslint.md

ts-utils.md

tile.json