Typescript: --noImplicitThis code fix?

Created on 11 Dec 2018  路  8Comments  路  Source: microsoft/TypeScript

Search Terms

noImplicitThis noImplicitAny code fix this annotation

Suggestion

14786 added a code fix for --noImplicitAny failures. Can we have the same for --noImplicitThis?

In cases where the this can be inferred for all locations that directly call a function, can TypeScript make a best guess of what the this type is meant to be?

Use Cases

In older code that uses fancy function assignments and isn't yet onboarded onto --noImplicitThis, it can be a bit of a pain to add them in.

Examples

interface NameBox {
  name: string;
  printName(): void;
}

// Code fix suggestion to add a `this: NameBox`?
function printName() {
  console.log(this.name);
}

const createNameBox = (name: string): NameBox => ({
    name,
    printName,
});

This example seems like it could be an inferrable one, since we can tell that printName is used as a member of a NameBox.

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
In Discussion Suggestion help wanted

All 8 comments

Duplicate of #28347? 馃槃

Heh, I didn't think it was - that looked more like a request to still surface the complaint when the rule is off, and maybe is a superset of this issue... but if that's incorrect, even better!

What is the PR that it was committed in?

I think you're right about the codefix - I don't think we actually have a quickfix for noImplicitThis right now, though I imagine it's just an extension of the inferFromUsage quickfix we already offer.

cc @sandersn

@weswigham / @sandersn would you accept PRs for this? The lack of the help wanted label is a deterrent.

I don't see why not.

I think the easiest way would be to just register the inferFromUsage code fix with the noImplicitThis errors; the inference code is going to be very similar and there鈥檚 already code to support inserting annotations in a wide array of places.

That said, the code is somewhat rough, so let me know if you need help getting unstuck anywhere.

This was resolved by #31138! 馃帀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RyanCavanaugh picture RyanCavanaugh  路  205Comments

disshishkov picture disshishkov  路  224Comments

xealot picture xealot  路  150Comments

blakeembrey picture blakeembrey  路  171Comments

Taytay picture Taytay  路  174Comments