Auto Null Chaining is a VS Code extension that automatically inserts optional chaining (?.) into JavaScript, TypeScript, JSX, and TSX files. It scans the selected code (or the whole file if nothing is selected) for unsafe property accesses and transforms them into safe optional chaining expressions.
Features
Detects unsafe MemberExpression patterns such as user.profile.name or items[0].title.
Converts them to user?.profile?.name and items?.[0]?.title respectively.
Works inside JSX expressions (<div>{user.name}</div> → <div>{user?.name}</div>).
Does not generate guard clauses; it only inserts ?..
Keyboard shortcuts:
macOS: ⌘ + ⌥ + .
Windows/Linux: Ctrl + Alt + .
Usage
Open a JavaScript/TypeScript/JSX/TSX file.
Place the cursor anywhere in the file or select a block of code you want to transform.
Run the command Insert Optional Chaining via the Command Palette (⇧⌘P → Insert Optional Chaining) or use the keyboard shortcut.
The selected code (or the whole file) is replaced with the transformed version.
Installation (Development)
# Clone the repository (or copy the generated folder)
cd /Users/dharmadurai/.gemini/antigravity/scratch/auto-null-chaining-extension
npm install
npm run compile # builds the extension into ./out
Open the folder in VS Code and press F5 to launch a new Extension Development Host where you can test the command.
Implementation Details
Parsing – Uses @babel/parser with plugins for typescript, jsx, and modern syntax.
Transformation – Traverses the AST with @babel/traverse. For each MemberExpression that is not already optional and whose object is not a CallExpression, the node’s optional flag is set to true.
Code Generation – @babel/generator recreates the source code while preserving formatting.
VS Code Integration – The command autoNullCheck.insertOptionalChaining is registered in extension.ts and bound to the shortcuts defined in package.json.
Limitations & Edge Cases
Already safe expressions (user?.name) are left untouched.
Optional calls (user?.getName()) are not altered.
Property accesses on the result of a function call (getUser().name) are ignored because the function could return null.
Dynamic expressions that cannot be safely converted are also ignored.
Contributing
Feel free to open issues or submit pull requests. Make sure to run npm run compile before committing.