Refactoring TypeScript
Refactoring means updating the source code without changing the behaviour of the application. Refactoring helps you keep your code solid, dry, and easy to maintain.
Move refactorings
Besides moving files and folders, IntelliJ IDEA lets you move TypeScript top-level symbols. The Move Symbol Refactoring works for classes, functions, and variables in ES6 modules.
Move a class, a function, or a variable
Select the symbol to move.
Press F6 or select
from the main menu or from the context menu of the selection. Alternatively, choose or press Control+Alt+Shift+T, then choose from the list.The Move Module Members dialog opens.
Specify the destination file and select the members to move.
By default, IntelliJ IDEA automatically raises the visibility of the members to the required level. If you want to keep the visibility level unchanged, click As is in the Visibility.
Pull Class Members Up refactoring
The Pull Class Members Up refactoring moves class methods upwards in the class hierarchy – from the current class to a superclass or to the interface which it implements.
Suppose you have a class AccountingDepartment
that extends an abstract class Department
and implements an interface ReportingDepartment
.
Example 1: Moving a class method to a superclass
In this example, the PrintMeeting()
method is moved from AccountingDepartment
to Department
.
Example 2: Moving a class method to an interface
In this example, the PrintMeeting()
method is copied from the AccountingDepartment
class to the ReportingDepartment
interface.
Move the methods of a class to a superclass or an interface
Place the caret anywhere inside the class from which you want to pull the members up.
Select Pull Members Up dialog opens.
from the main menu or from the context menunu. TheFrom the list, select the superclass or the interface where you want to move the methods.
To pull a method up, select the checkbox next to it in the Members to be pulled up list. If applicable, select the Make abstract checkbox next to the method to move.
Rename refactorings
Besides Renaming files and folders, which is available in the context of any language, you can also rename classes, methods, variables, parameters, and fields. IntelliJ IDEA changes the name of the symbol in its declaration and by default all its usages in the current project.
The Rename refactoring is performed inplace, but you can press Shift+F6 to configure the refactoring scope in the Rename dialog.
To open the dialog by default, open the Settings dialog (Control+Alt+S), go to , and select the In modal dialogs option in the Specify refactorings options area.
In the editor, select the class, method, variable, or field to rename and press Shift+F6 or choose
from the context menu or from the main menu.In the field with canvas, specify the new name of the symbol. Type the name or select an appropriate one from the list.
Optionally:
Click next to the highlighted symbol to open the Also rename in popup and select the Search in comments and strings and Search for text occurrences checkboxes to rename the usages of the symbol in comments, string literals, and text.
Optionally:
To open the Rename dialog with more options, press Shift+F6 once again.
Select the Search in comments and strings checkbox to rename the usages of the symbol in comments, documentation comments, and string literals.
Select the Search for text occurrences checkbox to rename the matched symbol in texts in HTML and other files included in the project.
Select the Search in JavaScript files checkbox to rename the usages of the symbol in generated JavaScript code.
Select the Search for dynamic references checkbox to rename the dynamic usages of the symbol.
Note that including dynamic usages in the refactoring may cause erroneous renaming as shown in the example below. Here
target
inconsole.log(e.target)
can be changed tomyTarget
becausee
has the typeany
, which means it could also bemyInt
.interface myInt { target: string } function onClick(e: any) { console.log(e.target); }interface myInt { myTarget: string } function onClick(e: any) { console.log(e.myTarget); }
To avoid erroneous renaming, preview the changes before applying them.
By default, in the Refactoring Preview tool window, all the dynamic usages of a symbol are marked as excluded and grouped under the Dynamic references in code to <symbol> node. To apply the refactoring to a usage, select Include from its context menu.
Keep the names of classes and containing files in compliance
When you rename a class, IntelliJ IDEA also suggests renaming the file if it has the same name. If you accept the suggestion, IntelliJ IDEA updates the name of this file in import statements in other files.
If you reject this suggestion, you can rename the file at any time later using the Rename file... intention action. This is useful if you have just created a new file but then came up with a better name when started typing a class or interface in it.
Another intention action suggests moving the class to a new file with the corresponding name. The format of the suggested filename is determined by the style chosen from the Filename convention list on the Code Style: JavaScript page.
Keep the name of a file in compliance with the name of the corresponding class
Place the caret at the name of the class and press Alt+Enter.
From the intentions list, choose Rename file to <class_name.ts> to match class name or Move class <class_name> to file <class_name.ts>.
Extract/Introduce refactorings
IntelliJ IDEA provides various Extract refactorings to introduce parameters, variables, constants, fields, methods, and functions. To run any of these refactorings, select the expression to refactor and choose . You can select an entire expression or place the caret anywhere inside it and IntelliJ IDEA will help you with the selection.
Introduce Parameter
Use the Introduce Parameter refactoring to replace an expression in the calls of a function with a parameter. IntelliJ IDEA will update the declaration and the calls of the function accordingly. The default value of the new parameter can be initialized inside the function body or passed through function calls.
Suppose you have a piece of code with a hardcoded "Hello, "
in the function greeter()
.
"Hello, "
with a greeting
parameter. The new greeting
parameter can be extracted as optional or as required.Example 1: Extracting an optional parameter
A new parameter greeting
is extracted as an optional parameter. The new parameter is added to the definition of greeter()
using the function default parameter syntax. The call of greeter()
is not changed.
Example 2: Extracting a required parameter
In this example, a new parameter greeting
is extracted as a required parameter. So the corresponding function call (document.body.innerHTML = greeter(user);
is changed accordingly.
Introduce a parameter
In the editor, place the caret within the expression that you want to convert into a parameter and press Control+Alt+P or select
from the context menu.Alternatively, do one of the following:
Press Control+Alt+Shift+T and select
.Go to
.
If several expressions are detected in the current caret location, select the required one from the Expressions list.
If more than one occurrence of the selected expression is found, select Replace this occurrence only or Replace all occurrences from the Multiple occurrences found list. Finally, the popup for configuring the refactoring appears.
Select the Generate JSDoc to have a JSDoc comment block generated. This may be helpful if you need to specify a custom default parameter value.
Choose where the new parameter will be initialized and specify its default value, if applicable:
If the Optional parameter checkbox is selected, the parameter will be initialized with the default value in the function body.
If the Optional parameter checkbox is cleared, the default parameter value will be passed through the existing function calls. All the function calls will change according to the new function signature and a parameter initialization will be added to the function body.
Initially, IntelliJ IDEA accepts the expression where the refactoring is invoked as the default value. In most cases, you do not need to change it. If it is still necessary, specify another default value in the JSDoc comment in the format
@param <parameter name> - <default value>
.Learn more about optional and default parameters from the TypeScript official website.
Accept one of the suggested parameter names by double-clicking it in the list or specify a custom name in the field with red canvas. Press Enter when ready.
Choosing the refactoring mode
You can extract a parameter right in the editor (in the in-place mode) as described above or use the Introduce Parameter dialog. These two approaches are rather similar, the difference is as follows:
Previewing the results of the refactoring.
In the dialog, you can click Preview and examine the expected changes in the dedicated tab of the Find tool window. In the in-place mode, this functionality is not available.
Specifying the default parameter value.
In the dialog, IntelliJ IDEA suggests the default parameter value in the Value field where you can accept the suggestion or specify another value. In the in-place mode, IntelliJ IDEA treats the expression where the refactoring is invoked as the default parameter value. To specify another value, you have to use a JSDoc comment block.
Introduce Variable
Use the Introduce Variable refactoring to replace an expression with a function-scoped variable (var), a block-scoped variable (let), or a block-scoped constant (const). This refactoring makes your source code easier to read and maintain. It also helps you avoid using hardcoded constants without any explanations about their values or purposes.
Introduce a variable
In the editor, select the expression to convert into a variable and press Control+Alt+V and select
from the context menu.Alternatively, do one of the following:
Press Control+Alt+Shift+T and select
.Go to
.
If several expressions are detected in the current caret location, select the required one from the Expressions list.
If more than one occurrence of the selected expression is found, select Replace this occurrence only or Replace all occurrences from the Multiple occurrences found list.
Finally, the popup for configuring the refactoring appears.
From the list, select the statement to use in the declaration of the new variable:
Choose var to introduce a function-scoped variable. This variable can be declared in the enclosing function or outside any function.
Choose let to introduce a block-scoped variable.
Choose const to introduce a block-scoped constant.
Accept one of the suggested parameter names by double-clicking it in the list or specify a custom name in the field with red canvas. Press Enter when ready.
Choosing the refactoring mode
You can extract a variable right in the editor (in the in-place mode) as described above or use the Introduce Variable dialog. By default, IntelliJ IDEA runs the Introduce Variable refactoring in the in-place mode. To use the Extract Variable dialog, open the Settings dialog (Control+Alt+S), go to Editor | Code Editing, and select the In modal dialogs option in the Refactorings area.
Introduce Constant
Use the Introduce Constant refactoring to replace an expression with a constant. This refactoring makes your source code easier to read and maintain. It also helps you avoid using hardcoded constants without any explanations about their values or purposes.
Suppose you have a fragment of code with hardcoded Department name:
.
With the Introduce Constant refactoring, you can replace the hardcoded Department name
with a constant. The scope of the extracted constant depends on the context in which the new constant is declared (inside the enclosing method, as a field of the class, or outside any class).
Example 1: The introduced constant departmentName is declared inside the enclosing method printName()
Example 2: The introduced constant is declared as the _departmentName field of the enclosing class AccountingDepartment
Example 3: The introduced constant departmentName is declared outside any class
Introduce a constant
In the editor, select the expression to convert into a constant and press Control+Alt+C or select
from the context menu.Alternatively, do one of the following:
Press Control+Alt+Shift+T and select
.Go to
.
If several expressions are detected in the current caret location, select the required one from the Expressions list.
Select the scope for the new constant:
If IntelliJ IDEA detects several occurrences of the expression, select whether you want to replace all of them or only the one where the refactoring was invoked.
Accept one of the suggested parameter names by double-clicking it in the list or specify a custom name in the field with red canvas. Press Enter when ready.
Introduce Field
The Introduce Field refactoring declares a new field and initializes it with the selected expression. The original expression is replaced with the usage of the field.
Suppose you have the following code:
_calcArea
is introduced. The examples illustrate three different ways to initialize the introduced field.Example 1: The introduced field _calcAreais initialized in the enclosing method get Area()
Example 2: The introduced field _calcArea is initialized in its declaration
Example 3: The introduced field _calcArea is initialized in the constructor of the class
Introduce a field
In the editor, select the expression to convert into a constant and press Control+Alt+F or select
from the context menu.Alternatively, do one of the following:
Press Control+Alt+Shift+T and select
.Go to
.
If IntelliJ IDEA detects several occurrences of the expression, select whether you want to replace all of them or only the one where the refactoring was invoked.
In the popup, choose where the new field will be initialized:
When initialized in a field declaration or in a constructor, the new field can be introduced with a readonly modifier. To do that, select the Make readonly checkbox.
Choose the field visibility, the available options are Public, Private, and Protected. Learn about field visibility modifiers from the TypeScript official website
Accept one of the suggested parameter names by double-clicking it in the list or specify a custom name in the field with red canvas. Press Enter when ready.
Choosing the refactoring mode
By default, IntelliJ IDEA runs the Introduce Field refactoring right in the editor (in the in-place mode), as described above.
To use the Extract Field Dialog, open the Settings dialog (Control+Alt+S), go to Editor | Code Editing, and select the In modal dialogs option in the Refactorings area.
Extract Method
The Extract Method refactoring lets you create a named method or function with the extracted code. When the Extract Method refactoring is invoked, IntelliJ IDEA detects the variables that are the input for the selected code fragment and the variable that is the output for it. The detected output variable is used as the return value for the extracted method or function.
Example 1: Extracting a global method from an expression inside another method
In this example, a globally scoped method NewMethod()
is extracted from the let c = a + b;
expression. The parameters for the extracted method are retrieved from the let c = a + b;
expression.
Example 1.1: A function declaration is generated
Example 1.2: The extracted function is declared inside an expression
Example 2: Extracting a method with declaration inside the enclosing method
In this example, a method NewMethod()
is extracted from the let c = a + b;
expression. The destination scope function MyFunction
is chosen.
Example 3: Extracting a method from an expression outside any method
A method NewMethod()
is extracted from the var e = MyFunction(4, 6);
expression that is outside any method. The extracted method is globally scoped.
Extract a function
In the editor, select a code fragment to convert into a function and press Control+Alt+M or select
from the context menu.Alternatively, do one of the following:
Press Control+Alt+Shift+T and select
.Go to
.
If the selected expression is inside another function, choose the destination scope from the list:
To open the Extract Function Extract Function dialog with more options, press Control+Alt+M once again. In this dialog, you can choose whether the extracted function will be declared through a generated function declaration or inside an expression and configure the set of variables to be passed as parameters. See Examples above.
Open the Extract Function dialog by default
open the Settings dialog (Control+Alt+S), go to Editor | Code Editing, and select the In modal dialogs option in the Refactorings area.
Extract Type Alias
Use this refactoring to convert a type declaration expression into a type alias and replace all the occurrences of this expressions with this alias.
Suppose you have the following fragment of code with a { z: number }
type declaration:
MyNewAlias
is extracted from the { z: number }
type declaration: Extract a type alias
In the editor, place the caret within the expression that you want to replace with a type alias and select
from the context menu or from the main menu.If several expressions are detected in the current caret location, select the required one from the Expressions list.
If more than one occurrence of the selected expression is found, select Replace this occurrence only or Replace all occurrences from the Multiple occurrences found list.
In the field, type the name of the type alias and press Enter when ready.
Extract Superclass
The Extract Superclass refactoring creates a new abstract class based on the members of the current class. The created abstract class is extended automatically.
Suppose you have a class AccountingDepartment
and you expect that the printName()
method from it will be re-used.
Department
and include the printName
and the Name
field in it. Extract a superclass
Place the caret anywhere inside the class from which you want to extract a superclass.
Select Extract Superclass dialog opens.
from the main menu or from the context menu. TheSpecify the name of the new superclass and select the checkboxes next to the class members you want to include in it.
In the Destination file field, specify the location of the file where the new class will be. By default, the field shows the path to the current file where the refactoring was invoked.
Choose Extract Superclass. IntelliJ IDEA creates a new class and marks the source class with
extends
.To create a superclass and replace the references to the source class with references to the superclass in parameters of methods, choose Extract superclass and use it where possible. IntelliJ IDEA shows the proposed changes in the Refactoring Preview pane of the Find tool window.
Extract Interface
The Extract Interface refactoring creates a new interface based on the members of the current class. The created interface will be implemented automatically.
Suppose you have a class AccountingDepartment
and you expect that the generateReports()
method from it will have other implementations.
DepartmentInterface
interface and include the generateReports()
in it. Extract an interface
Place the caret anywhere inside the class from which you want to extract an interface.
Select Extract Interface dialog opens.
from the main menu or from the context menunu. TheSpecify the name of the new interface and select the checkboxes next to the class members you want to include in it.
In the Destination file field, specify the location of the file where the new interface will be. By default, the field shows the path to the current file where the refactoring was invoked.
Choose Extract Interface. IntelliJ IDEA creates a new interface and marks the source class as its implementation.
To create an interface and replace the references to the source class with references to the interface in parameters of methods, choose Extract interface and use it where possible. IntelliJ IDEA shows the proposed changes in the Refactoring Preview pane of the Find tool window.
Introduce Object or Array Destructuring
Destructuring lets you easily unpack values from arrays and objects into variables. This functionality has a very concise syntax that is often used when you need to pass data in your application. For more information, refer to the TypeScript official website.
In IntelliJ IDEA, you can invoke destructuring using an intention action Alt+Enter. With the Replace with object/array destructuring action, the original assignment is removed. To keep the assignment, use Introduce object/array destructuring.
Replace the original assignment
Place the caret at the value from an array or an object and press Alt+Enter.
From the list, select Replace with object destructuring or Replace with array destructuring.
If some of the values from an array or an object are not used, these elements will be skipped:
Keep the original assignments
Place the caret at the value from an array or an object and press Alt+Enter.
From the list, select Introduce object destructuring or Introduce array destructuring.
Generate destructuring parameters for a function
Place the caret at the parameters of a function and press Alt+Enter.
From the list, select Convert parameters to object.
Inline refactorings
Inline refactorings are opposite to Extract refactorings.
Example 1: Inline Variable
The Inline Variable refactoring replaces a redundant usage of a variable or a constant with its initializer. This type of refactoring is available only for block-scoped and function-scoped variables.
Example 2: Inline Method
The Inline Method/Inline Function refactoring results in placing the body of a method or a function into the body of its caller(s); the method/function itself is deleted.
In the example below, the body of Sum()
is placed in the body of Multiplication()
.
Run an Inline refactoring
In the editor, place the caret at the symbol to be inlined and press Control+Alt+N or select
from the context menu or from the main menu.
Change Signature refactoring
Use the Change Signature refactoring to change the name of a function, its visibility, and return type, to add, remove, reorder, and rename parameters, and to propagate new parameters through the hierarchy of calls.
You can also add a parameter using the Introduce Parameter refactoring.
In the example below, the function eat()
is renamed to feed()
and a new boolean
parameter isMammal
is introduced.
Invoke Change Signature
In the editor, place the caret within the name of the function to refactor and press Control+F6 or choose Refactor | Change Signature from the context menu or from the main menu. The Change Signature dialog opens.
Rename a function
In the Change Signature dialog Control+F6, edit the Name field.
Change the return type of a function
In the Return type field, specify the type of the value that the function returns. If the field is empty, the return type is treated as
void
. Learn more about the return type from the TypeScript official website.
Change the visibility of a function
From the Visibility list, select a function modifier, the available options are public (default), private, and protected.
Manage the function parameters
In the Change Signature dialog Control+F6, use the table of parameters and the buttons to the right of it:
To add a parameter, click Alt+Insert and specify the name of the new parameter and its type. Specify the default value of the parameter or the value to be passed through function calls.
If necessary, propagate the new parameter to the functions that call the current function.
To remove a parameter, click any of the cells in the corresponding row and click Alt+Delete.
To reorder the parameters, so required parameters are listed before optional ones, use Alt+ArrowUp and Alt+ArrowDown. Learn more about required and optional parameters from the TypeScript official website.
To rename a parameter, edit the Name field.
Propagate a parameter along the hierarchy of calls
In the Change Signature dialog Control+F6, select the parameter and click . The Select Methods to Propagate New Parameters dialog opens. The left-hand pane shows the hierarchy of function calls. When you select a function, the right-hand pane shows its code and the code of the function it calls in the Caller Method and Callee Method fields respectively.
In the left-hand pane, select the checkboxes next to the functions where you want to propagate the parameter and click OK.
Preview the changes and complete the refactoring
In the Change Signature dialog Control+F6, click Preview.
In the Refactoring Preview tab of the Find tool window, view the expected changes, make the necessary adjustments, and click Do Refactor when ready.