Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy the inferred type of an untyped function (TypeScript) in Visual Studio Code when its very long

(See Screenshot) Screenshot of function when hovering with mouse

I have this function with a really long untyped object returned, I want to copy the inferred type of that object because it's way too long to do manually, and then I want to make class/interface of it, example:

export class PatientTables {
  emsf: string;
  cadNumber: string;
  // and so on
}

is there a way to copy it from somewhere as it seems Visual Studio Code already has it assorted somewhere, as you can see in the picture (48 more), how can I make it show the rest and copy it? thanks!

like image 571
Elazar Zadiki Avatar asked May 04 '20 11:05

Elazar Zadiki


People also ask

How do I enable quick fix in VS Code?

Code Actions = Quick Fixes and refactorings#Clicking on the Code Action lightbulb or using the Quick Fix command Ctrl+. will display Quick Fixes and refactorings. If you'd just like to see refactorings without Quick Fixes, you can use the Refactor command (Ctrl+Shift+R).

How do you replace all variables in VS Code?

Rename All Occurrences If you select a variable/method and hit F2, you can edit the name and it will change every instance of that variable's name throughout the entire current working project.


4 Answers

You can get the type from the following code:

function createPatientTables() {
    return {
        foo: 'hello world',
        bar: 123
    };
}

type PatientTables = ReturnType<typeof createPatientTables>;
like image 52
Xinan Avatar answered Oct 12 '22 23:10

Xinan


One approach is to use the tsc command line tool. If you can isolate the file so that there are no dependencies, then you can run:

tsc filename.ts --declaration --emitDeclarationOnly

The resulting filename.d.ts file will include the generated type.

like image 22
mrcrowl Avatar answered Oct 13 '22 00:10

mrcrowl


Right click the function name, choose "refactor", then "Infer function return type".

like image 34
ZYinMD Avatar answered Oct 13 '22 01:10

ZYinMD


Use this extension (JSON to TS).

This doesn't directly answer your question, but I think it solves your problem. The extension takes JSON and converts it into TypeScript interfaces.

enter image description here

like image 26
jrasm91 Avatar answered Oct 13 '22 01:10

jrasm91