jackbsteinberg / get-originals-rewriter

BSD 3-Clause "New" or "Revised" License
0 stars 0 forks source link

Prototype: use TypeScript/ts-morph for type-safe console removal #13

Closed domenic closed 5 years ago

domenic commented 5 years ago

This pull request is some hacked-together, do-not-merge code showing a technique that uses TypeScript and ts-morph to do the console removal.

In particular, instead of just looking if the base of the call expression is an identifier named "console", it looks at the TypeScript-compiler-determined type of the expression, and checks if that type is named "Console". You can see how this helps with the edge cases, such as #12, in the newly-added test.

Things to note:


What to do with this?

I think we are going to need this technique (in particular, need an AST with type information) for replacing method calls/getters/setters. So we're going to need this infrastructure at some point.

We could either:

domenic commented 5 years ago

I've pushed an additional commit which shows what switching entirely to this infrastructure looks like. In that world we stop using the jscodeshift API entirely. In that case jscodeshift becomes a pretty large dependency for something that largely just wraps the read/write process, so when this project approaches "finished" we might want to consider removing it. (But for now I think it's enough of a help to keep around.)

I'll also note that https://ts-ast-viewer.com/ is helpful for seeing the world the way ts-morph sees it.

domenic commented 5 years ago

Further notes. As expected, TypeScript doesn't do global type inference. So if you try

function foo(x) {
    x.log();
}

foo(console);

in the AST viewer, the x in x.log will be noted as having type any. Not great.

However, in JS mode (use the options menu on the right of the AST viewer; this PR is in JS mode) it respects JSDoc comments. So given

/**
 * @param {Console} x
 */
function foo(x) {
    x.log();
}

foo(console);

it correctly figures out that x in x.log is a Console instance (and even finds the built-in type definition for it).

More on type-checking in JS files at https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html

jackbsteinberg commented 5 years ago

So it sounds like we can create a really robust system using TypeScript, as long as we make sure we're using JSdoc comments properly

domenic commented 5 years ago

Closing as this has been incorporated into the main repo!