Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.match issues with TypeScript and fromCapture #898

Closed
j4k0xb opened this issue Feb 4, 2023 · 3 comments · Fixed by #902
Closed

.match issues with TypeScript and fromCapture #898

j4k0xb opened this issue Feb 4, 2023 · 3 comments · Fixed by #902

Comments

@j4k0xb
Copy link

j4k0xb commented Feb 4, 2023

The m.match function doesn't seem to properly work with TypeScript. Example from the jsdoc:

import * as m from '@codemod/matchers';

let id: m.CapturedMatcher<t.Identifier>;
const idPlusIdMatcher = m.binaryExpression(
  '+',
  (id = m.capture(m.identifier())),
  m.fromCapture(id)
);

export default function() {
  return {
    BinaryExpression(path: NodePath<t.BinaryExpression>): void {
      m.match(idPlusIdMatcher, { id }, path.node, ({ id }) => {
        path.replaceWith(t.binaryExpression('*', id, t.numericLiteral(2)));
      });
    }
  };
}

image

This can be fixed by importing from ../matchers instead, because the published package doesn't contain src.

import * as m from '../../src/matchers'

import * as m from '../../src/matchers'

Another thing I noticed is that .fromCapture only works with captured primitives like strings, not matchers themselves:

// fails
const id = m.capture(m.identifier())
const idPlusIdMatcher = m.binaryExpression('+', id, m.fromCapture(id))
// works
const idValue = m.capture(m.anyString())
const idPlusIdMatcher = m.binaryExpression(
  '+',
  m.identifier(idValue),
  m.identifier(m.fromCapture(idValue))
)

Would be nice if both ways work to compare whole code structures

And when matching with containers it shouldn't narrow the type:

if (idPlusIdMatcher.match(ast)) {
  console.log(path.node) // TS says "t.BinaryExpression", at runtime it's e.g. "t.Program"
@eventualbuddha
Copy link
Collaborator

Fixed in v1.3.1.

@eventualbuddha
Copy link
Collaborator

And I liked your suggestion for the behavior of fromCapture, so I changed that in v1.4.0.

@eventualbuddha
Copy link
Collaborator

And I also have an idea for the type narrowing thing. Stay tuned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants