babel-type-scopes

raw JSON →
1.1.0 verified Sat Apr 25 auth: no javascript

Utility functions for looking up and working with Flow and TypeScript type scopes in Babel. Version 1.1.0 provides four main functions: isTypeScope, getClosestTypeScopePath, getOwnTypeBindings, and getTypeBinding. These helpers identify whether a Babel path creates a type scope, find the nearest ancestor type scope, retrieve type bindings defined in the current scope, and search for type bindings up the scope chain. The package supports both Flow and TypeScript, and is intended for Babel plugin or tool authors. It is lightweight with no production dependencies. Released in 2018, the library is stable but sees infrequent updates. Similar functionality exists in @babel/traverse, but this package provides more targeted scope inspection.

error Cannot find module 'babel-type-scopes'
cause Package not installed or missing from node_modules.
fix
Run 'npm install babel-type-scopes' or 'yarn add babel-type-scopes'.
error TypeError: isTypeScope is not a function
cause Incorrect import syntax (e.g., default import instead of named import).
fix
Use 'import { isTypeScope } from 'babel-type-scopes';'
error TypeError: Cannot read property 'kind' of undefined
cause No type binding found in the scope chain for the given name.
fix
Ensure the name exists as a type binding; consider checking getOwnTypeBindings first.
gotcha The package only considers type scopes (type declarations, interface, etc.). Regular variable scopes are not covered.
fix Use @babel/traverse's getBinding for non-type bindings.
gotcha getClosestTypeScopePath may return the current path if it is a type scope, which may be unexpected.
fix Check if the returned path is the same as the input; if so, the path itself is a type scope.
gotcha getTypeBinding searches only type scopes; it does not look up regular bindings. This may cause confusion if a binding is declared with 'let' or 'const'.
fix Use getTypeBinding only for type-level bindings (types, interfaces). For value bindings, use @babel/traverse's scope.getBinding.
npm install babel-type-scopes
yarn add babel-type-scopes
pnpm add babel-type-scopes

Parses TypeScript code, traverses AST, and demonstrates each exported function on a type alias.

import { isTypeScope, getClosestTypeScopePath, getOwnTypeBindings, getTypeBinding } from 'babel-type-scopes';
import { parse } from '@babel/parser';
import traverse from '@babel/traverse';

const code = `type Foo = string; let x: Foo = 'hello';`;
const ast = parse(code, { plugins: ['typescript'] });
traverse(ast, {
  TSTypeAliasDeclaration(path) {
    console.log(isTypeScope(path)); // true
    const scopePath = getClosestTypeScopePath(path);
    console.log(scopePath.node.type); // TSTypeAliasDeclaration
    const bindings = getOwnTypeBindings(scopePath);
    console.log(Object.keys(bindings)); // ['Foo']
    const binding = getTypeBinding(path, 'Foo');
    console.log(binding.kind); // 'declaration'
  }
});