Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode keyboard shortcut for 'Assign expression result to new local variable'?

In Eclipse, there's this really handy shortcut, mapped to CTRL + 2 + L by default, which works when an expression is selected. What it does is to create a new local variable to hold the result of the expression. For example...

this.doSomeCalculation();

If the mouse cursor is positioned over the line above, CTRL + 2 + L will turn the line into...

double someCalculation = this.doSomeCalculation()

I find myself using this shortcut a lot when coding Java. Is there something similar available for editing Typescript in Visual Studio Code?

like image 681
Alan47 Avatar asked Mar 13 '17 11:03

Alan47


People also ask

What is Ctrl K in VS Code?

To launch the Define Keybinding widget, press Ctrl+K Ctrl+K. The widget listens for key presses and renders the serialized JSON representation in the text box and below it, the keys that VS Code has detected under your current keyboard layout.

What is Ctrl Shift P in VS Code?

You can define a keyboard shortcut for any task. From the Command Palette (Ctrl+Shift+P), select Preferences: Open Keyboard Shortcuts File, bind the desired shortcut to the workbench.

What does Ctrl d do in VS Code?

Ctrl+D selects the word at the cursor, or the next occurrence of the current selection. Tip: You can also add more cursors with Ctrl+Shift+L, which will add a selection at each occurrence of the current selected text.

What is Alt Shift F VS Code?

Search for Format Document to find out which keybinding is currently able to format your code. You can choose to continue with the default keybinding or change it by clicking on the edit icon on the left of the command you're interested in changing. In this case, you would simply hit Alt + Shift + F and that's it.


2 Answers

You can assign keybinding to refactorings such as extract constant.

Here's a keybinding that binds ctrlshifte to the extract constant refactoring:

{
  "key": "ctrl+shift+e",
  "command": "editor.action.refactor",
  "args": {
    "kind": "refactor.extract.constant",
    "apply": "first"
  }
}

This keybinding will work in JavaScript and TypeScript (and in any other languages that have an extract constant refactoring)

P.S. Here is a slight variation for JS/TS that lets a single keybinding work for both extract type and extract constant:

{
  "key": "ctrl+shift+e",
  "command": "editor.action.refactor",
  "args": {
    "kind": "refactor.extract",
    "preferred": true,
    "apply": "first"
  }
}
like image 59
Matt Bierner Avatar answered Sep 28 '22 01:09

Matt Bierner


You can select an expression and then:

In Mac:

Opt + Cmd + V

In Windows:

Ctrl + Alt + V

like image 23
Felipe Pereira Avatar answered Sep 28 '22 00:09

Felipe Pereira