microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.08k stars 12.5k forks source link

Refactoring: Generate type annotation from inferred type #32319

Open octogonz opened 5 years ago

octogonz commented 5 years ago

Search Terms

refactoring quick fix add inferred type

Suggestion

VS Code should provide a refactoring command for generating a type annotation.

Use Cases

In our code base, we use the TSLint's typedef rule to enforce type annotations. For example:

// TSLINT ERROR
const map = this.getMap();
const value = map.getValue(someKey);

// GOOD
const map: Map<string, CatalogItem> = this.getMap();
const value: CatalogItem = map.getValue(someKey);

It's true that these types can usually be inferred by the compiler. However, requiring people to write explicit annotations makes code more readable, especially in situations where IntelliSense is unavailable. For example: When reviewing a GitHub pull request, or printing a Git history, we get no help from IntelliSense.

Details

VS Code should provide a refactoring command for generating a type annotation. For example, if I right-click on map in this code...

const map = this.getMap();

...then I should be able to do Refactor -> Add Type, and it will convert it to the good form shown above.

Although this is a super easy operation for the compiler engine, I cannot seem to find an implementation of this feature.

I found a couple projects typescript-plugin-add-type and typescript-plugin-proactive-code-fixes. However, they aren't usable:

Representing refactoring operations as compiler plugins doesn't seem like the best design:

Since the implementation is relatively simple, this seems like a good candidate for a built-in feature.

Checklist

My suggestion meets these guidelines:

AlCalzone commented 5 years ago

Duplicate of https://github.com/microsoft/TypeScript/issues/31163 (except that issue only included methods).

octogonz commented 5 years ago

Should that one be a dupe of this one then? :-P

AlCalzone commented 5 years ago

I'll let the TypeScript devs decide ;)

ethanresnick commented 5 years ago

Duplicate of #13199?

yw662 commented 1 year ago

I am doing some documentation for a project written in typescript when I realized that most of the function return values in that project is inferred, so there is nothing I can copy-paste. I can still hover the mouse over that function or whatsoever to copy the inferred type, but it is filled with ..., and I can find nowhere to get the full inferred type. Then I tried --declaration --emitDeclarationOnly, but what I get is no more than ReturnType<typeof foo>. So, after so many issues related to that, how can I get the inferred type literal so that I can include them in docs ?