I am looking for a shortcut that is available in Eclipse and called "extract local variable". It will assign the return value of the selected function invocation to a variable:
Is something similar available in VSC for Javascript and Typescript?
I am looking for a shortcut that is available in Eclipse and called "extract local variable". It will assign the return value of the selected function invocation to a variable:
Is something similar available in VSC for Javascript and Typescript?
Share Improve this question asked Feb 23, 2020 at 9:44 Frederik ClausFrederik Claus 6845 silver badges16 bronze badges 1- code.visualstudio.com/docs/editor/refactoring#_extract-variable – artanik Commented Feb 23, 2020 at 10:04
2 Answers
Reset to default 17You can use the "Refactor..." shortcut Ctrl+Shift+R to extract the expression to a constant. Example:
function main(){
return "foo".replace("o", "a")
}
Mark the expression "foo".replace("o", "a")
or the whole line → "Extract to constant in enclosing scope", name it to test
and the function will be refactored to the following:
function main(){
const test = "foo".replace("o", "a")
return test
}
There is also the "Quick Fix" command (Ctrl+.) for fixes and refactorings.
If you want an extra shortcut just for this action, define it manually in keybindings.json (docs):
{
"key": "shift+ctrl+alt+r",
"command": "editor.action.codeAction",
"args": {
"kind": "refactor.extract.constant"
}
}
A bit better implementation. Inline variable and extract to const without selection.
How to :
- Open system action ">Preferences: Open Keyboard Shortcuts (JSON)"
- Paste code.
code:
[
{
"key": "ctrl+alt+n",
"command": "editor.action.codeAction",
"args": {
"kind": "refactor.inline"
}
},
{
"key": "ctrl+alt+v",
"command": "runCommands",
"args": {
"commands": [
{
"command": "editor.action.selectToBracket",
"args": {
"selectBrackets": false
}
},
{
"command": "editor.action.codeAction",
"args": {
"kind": "refactor.extract.constant",
"apply": "first"
}
}
]
}
}
]
Ps. Sorry for intelliJ shortcuts.