babel-plugin-ts-optchain
raw JSON → 1.1.5 verified Sat Apr 25 auth: no javascript maintenance
Babel plugin that transforms optional chaining expressions (e.g., `obj?.prop`) for TypeScript using the ts-optchain approach. Version 1.1.5 (latest) is stable but unmaintained since 2020. Provides an alternative to TypeScript's native optional chaining for environments that don't support it, by converting `?.` into `_` wrapped calls. Works only with Babel, not tsc. No dependencies. Not recommended for new projects; prefer native optional chaining.
Common errors
error SyntaxError: Unexpected token '.' ↓
cause Babel is not set up to parse modern optional chaining syntax.
fix
Ensure babel.config.js includes the ts-optchain plugin and that you are using the correct Babel parser. Example: { plugins: ['ts-optchain'] }
error Cannot find module 'ts-optchain' ↓
cause Missing runtime dependency 'ts-optchain'.
fix
Install the package: npm install ts-optchain
error TypeError: oc(...).a.b is not a function ↓
cause Using oc() without calling the final property as a function (e.g., oc(obj).a.b instead of oc(obj).a.b()).
fix
Invoke the last property access as a function: oc(obj).a.b()
Warnings
deprecated Package is effectively unmaintained since 2020. Use TypeScript 3.7+ native optional chaining (obj?.prop) when possible. ↓
fix Migrate to native optional chaining and remove babel-plugin-ts-optchain.
gotcha Requires both 'babel-plugin-ts-optchain' and 'ts-optchain' packages to be installed. Missing one causes runtime errors. ↓
fix Run: npm install ts-optchain babel-plugin-ts-optchain
deprecated Babel plugin no longer necessary for TypeScript 3.7+. Native optional chaining is compile-time and more efficient. ↓
fix Remove the plugin and use TypeScript's native ?. operator.
Install
npm install babel-plugin-ts-optchain yarn add babel-plugin-ts-optchain pnpm add babel-plugin-ts-optchain Imports
- plugin wrong
import plugin from 'babel-plugin-ts-optchain';correctmodule.exports = { plugins: ['ts-optchain'] }; - default wrong
import babelPluginTsOptchain from 'babel-plugin-ts-optchain';correctmodule.exports = { plugins: ['ts-optchain'] }; - ts-optchain types wrong
import oc from 'ts-optchain';correctimport { oc } from 'ts-optchain';
Quickstart
// Install: npm install --save-dev babel-plugin-ts-optchain ts-optchain
// .babelrc
{
"plugins": ["ts-optchain"]
}
// Example TypeScript file
import { oc } from 'ts-optchain';
const obj = { a: { b: 'hello' } };
const val = oc(obj).a.b(); // returns 'hello'
const missing = oc(obj).x.y('default'); // returns 'default'
// Compiled output uses the oc function
console.log(val, missing);