WebStorm 2017.3 Help

Refactoring TypeScript

Refactoring means updating the structure of 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, WebStorm lets you move TypeScript top-level symbols. The Move Symbol Refactoring works for classes, functions, and variables in ES6 modules.

To move a class, a function, or a variable

  1. Select the symbol to move.
  2. Press F6 or choose Refactor | Move on the main menu or on the context menu of the selection.
  3. In the dialog box that opens, specify the destination file.

In the example below, the function changeSelectedPlaylists is moved from the PlayerActions.js file to the PlaylistsActions.js file. Note that an import statement for the types that changeSelectedPlaylists requires is added to PlaylistsActions.js. Also all the imports of changeSelectedPlaylists in the other files are updated.

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.

abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } } interface ReportingDepartment { generateReports(): void } class AccountingDepartment extends Department implements ReportingDepartment { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }

Example 1: Moving a class method to a superclass
In this example, the PrintMeeting() method is moved from AccountingDepartment to Department.

abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } } interface ReportingDepartment { generateReports(): void } class AccountingDepartment extends Department implements ReportingDepartment { constructor() { super("Accounting and Auditing"); } generateReports(): void { console.log("Generating accounting reports..."); } }

Example 2: Moving a class method to the interface
In this example, the PrintMeeting() method is copied from the AccountingDepartment class to the ReportingDepartment interface.

abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } } interface ReportingDepartment { generateReports(): void printMeeting(): void } class AccountingDepartment extends Department implements ReportingDepartment { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }

To move the methods of a class to a superclass or the interface

  1. Place the cursor anywhere inside the class from which you want to pull the members up.
  2. Choose Refactor | Pull Members Up on the main menu or on the context menu. The Pull Members Up dialog opens.
  3. From the drop-down list, choose the superclass or the interface where you want to move the methods.
  4. 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, functions, variables, and parameters. WebStorm changes the name of the symbol in its declaration and by default all its usages in the current project.

To rename a function, a class, or a variable

  1. In the editor, select the symbol to rename and press Shift+F6 or choose Refactor | Rename on the context menu or on the main menu.
  2. In the Rename dialog that opens, type the new name of the symbol.
  3. Optionally:
    • Select the Search in comments and strings and Search for text occurrences checkboxes to rename the usages of the function or the class in comments, string literals, documentation, HTML, and other files included in the project.
    • Select the Search JavaScript References checkbox to rename the usages of the function or the class in generated JavaScript code.
  4. If necessary, preview and apply the changes.

To rename a parameter

  1. Select the parameter in the editor and press Shift+F6 or choose Refactor | Rename on the context menu or on the main menu.
  2. In the text box with red canvas around the selected parameter, type the new parameter name.
  3. Press Enter to run the refactoring.

Extract refactorings

WebStorm 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 Refactor | Extract | <target>. You can select an entire expression or place the cursor anywhere inside it and WebStorm will help you with the selection.

Extract Parameter

Use the Extract Parameter refactoring to replace an expression in the calls of a function with a parameter. WebStorm 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().

function greeter(firstName : String, lastName : String) { return "Hello, " + firstName + " " + lastName; } document.body.innerHTML = greeter("Jane","User");
With the Extract Parameter refactoring, you can replace this hardcoded "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.

function greeter(firstName : String, lastName : String, greeting = "Hello, ") { return greeting + firstName + " " + lastName; } document.body.innerHTML = greeter("Jane","User");

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.

function greeter(firstName : String, lastName : String, greeting: string) { return greeting + firstName + " " + lastName; } document.body.innerHTML = greeter("Jane", "User", "Hello, ");

To extract a parameter

  1. In the editor, place the cursor within the expression that you want to convert into a parameter and press Ctrl+Alt+P or choose Refactor | Extract | Parameter on the context menu or on the main menu.
  2. If several expressions are detected in the current cursor location, select the required one in the Expressions list.
    ws_ts_extract_parameter_select_expression.png
  3. If more than one occurrence of the selected expression is found, choose Replace this occurrence only or Replace all occurrences in the Multiple occurrences found pop-up menu. Finally, the pop-up window for configuring the refactoring appears.
    ws_ts_extract_parameter_specify_parameter_name_and_type.png
  4. 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. Learn more from the JSDoc Official website.
  5. 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, WebStorm 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>.
  6. Accept one of the suggested parameter names by double-clicking it in the pop-up list or specify a custom name in the text box with red canvas. Press Enter when ready.
    ws_ts_extract_parameter_result.png

Choosing the refactoring mode
You can extract a parameter right in the editor (in the in-place mode) as described above or use the Extract Parameter dialog. These two approaches are rather similar, the difference is as follows:

  • Previewing the results of the refactoring.
    In the dialog box, 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 box, WebStorm suggests the default parameter value in the Value field where you can accept the suggestion or specify another value. In the in-place mode, WebStorm 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.

Extract Variable

Use the Extract 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.

function Multiplication(a : number, b : number) { let d = (a + b) * (a + b); return d; } var e = Multiplication(4, 6);
function Multiplication(a : number, b : number) { let c = a + b; let d = (c) * (c); return d; } var e = Multiplication(4, 6);

To extract a variable

  1. In the editor, select the expression to convert into a variable and press Ctrl+Alt+V or choose Refactor | Extract | Variable on the context menu or on the main menu.
  2. If several expressions are detected in the current cursor location, select the required one in the Expressions list.
    ws_ts_refactoring_extract_variable_inplace_select_expression.png
  3. If more than one occurrence of the selected expression is found, choose Replace this occurrence only or Replace all occurrences in the Multiple occurrences found pop-up menu.
    ws_ts_refactoring_extract_variable_inplace_multiple_occurrences.png
    Finally, the pop-up window for configuring the refactoring appears.
  4. In the pop-up menu, choose the statement to use in the declaration of the new variable:
    ws_ts_refactoring_extract_variable_inplace_choose_scope_type.png
  5. Accept one of the suggested variable names by double-clicking it in the pop-up list or specify a custom name in the text box. 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 Extract Variable dialog. By default, WebStorm runs the Extract Variable refactoring in the in-place mode. To use the Extract Variable dialog box, open the Settings/Preferences dialog (Ctrl+Alt+S) and click Editor | General. On the General page that opens, clear the Enable in-place mode checkbox in the Refactorings area.

Extract Field

The Extract 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:

class Rectangle { constructor(public height: number, public width: number) { this.height = height; this.width = width; } get area() { return this.calcArea(); } calcArea() { return this.height * this.width; } }
In all the three examples below, the same field, _calcArea is extracted. The examples illustrate three different ways to initialize the extracted field.

Example 1: The extracted field _calcAreais initialized in the enclosing method get Area()

class Rectangle { constructor(public height: number, public width: number) { this.height = height; this.width = width; } private _calcArea: number; get area() { this._calcArea = this.calcArea(); return this._calcArea; } calcArea() { return this.height * this.width; } }

Example 2: The extracted field _calcArea is initialized in its declaration

class Rectangle { constructor(public height: number, public width: number) { this.height = height; this.width = width; } private _calcArea = this.calcArea(); get area() { return this._calcArea; } calcArea() { return this.height * this.width; } }

Example 3: The extracted field _calcArea is initialized in the constructor of the class

class Rectangle { constructor(public height: number, public width: number) { this._calcArea = this.calcArea(); this.height = height; this.width = width; } private _calcArea: number; get area() { return this._calcArea; } calcArea() { return this.height * this.width; } }

To extract a field

  1. In the editor, select the expression to convert into a field and press Ctrl+Alt+F or choose Refactor | Extract | Field on the context menu or on the main menu.
  2. In the Extract Field Dialog that opens:
    • Specify the field name and type.
    • Choose where the new field will be initialized, the available options are:
    • Choose the field visibility, the available options are Public, Private, and Protected. Learn about field visibility modifiers from the TypeScript Official website
    ws_ts_extract_field_dialog_1.png

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, WebStorm 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

function MyFunction(a : number, b : number) { let c = a + b; let d = c * c; return d; }
function NewMethod(a: number, b: number) { let c = a + b; return c; } function MyFunction(a : number, b : number) { let c = NewMethod(a, b); let d = c * c; return d; }

Example 1.2: The extracted function is declared inside an expression

function MyFunction(a : number, b : number) { let c = a + b; let d = c * c; return d; }
let NewMethod = function (a: number, b: number) { let c = a + b; return c; }; function MyFunction(a : number, b : number) { let c = NewMethod(a, b); let d = c * c; return d; }

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.

function MyFunction(a : number, b : number) { let c = a + b; let d = c * c; return d; }
function MyFunction(a : number, b : number) { let NewMethod = function () { let c = a + b; return c; }; let c = NewMethod(); let d = c * c; return d; }

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.

var e = MyFunction(4, 6);
let NewMethod = function () { var e = MyFunction(4, 6); }; NewMethod();

To extract a function

  1. In the editor, select a code fragment to convert into a function and press Ctrl+Alt+M or choose Refactor | Extract | Method on the context menu or on the main menu.
  2. If the selected expression is inside another function, choose the destination scope from the pop-up list:
    ws_ts_extract_method_choose_scope.png
    • If you choose global, the extracted function will be declared outside any function, see Example 1 above.
    • To declare the extracted function inside the current enclosing function, choose function <current enclosing function name>, see Example 2 above.
  3. In the Extract Function dialog box that opens, specify the name of the new function.
  4. Choose how the function will be declared. By default, the Declare functional expression checkbox is cleared and WebStorm generates a function declaration, see Example 1.1 above.
    To declare the extracted function inside an expression, select the Declare functional expression checkbox, see Example 1.2 above.
  5. When extracting a globally scoped function, configure the set of variables to be passed as parameters. By default, all the variables from the specified scope are listed in the Parameters area.
    • To have a variable included in the parameter set, select the checkbox next to it.
    • To change the order of parameters, use the Move Up and Move Down buttons.
    ws_ts_extract_method_dialog.png
  6. In the Signature preview read-only area, check the declaration of the new function.

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:

function returnsObj(): { x : number, y : {z : number} } { return null } function anotherObjectReturned(): {x : number, y : {z : number} } { return null }
In the example below, a type alias MyNewAlias is extracted from the { z: number } type declaration:
type MyNewAlias = { z : number }; unction returnsObj(): { x : number, y : MyNewAlias } { return null unction anotherObjectReturned(): { x : number, y : MyNewAlias } { return null

To extract a type alias

  1. In the editor, place the cursor within the expression that you want to replace with a type alias and choose Refactor | Extract | Type Alias on the context menu or on the main menu.
  2. If several expressions are detected in the current cursor location, select the required one in the Expressions list.
    ws_ts_extract_type_alias_select_type_declaration_expression.png
  3. If more than one occurrence of the selected expression is found, choose Replace this occurrence only or Replace all occurrences in the Multiple occurrences found pop-up menu.
    ws_ts_extract_type_alias_multiple_occurrences.png
  4. In the text box, type the name of the type alias and press Enter when ready.
    ws_ts_extract_type_alias_specify_name.png

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.

class AccountingDepartment { name: string; printName(): void { console.log("Department name: " + this.name); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }
You can extract a superclass Department and include the printName and the Name field in it.
class Department { name: string; printName(): void { console.log("Department name: " + this.name); } } class AccountingDepartment extends Department { printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }

To extract a superclass

  1. Place the cursor anywhere inside the class from which you want to extract a superclass.
  2. Choose Refactor | Extract | Superclass on the main menu or on the context menu. The Extract Superclass dialog opens.
  3. Specify the name of the new superclass and select the checkboxes next to the class members you want to include in it.
  4. 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.
  5. Choose Extract Superclass. WebStorm 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. WebStorm 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.

abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } } class AccountingDepartment extends Department { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }
You can extract a DepartmentInterface interface and include the generateReports() in it.
abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); } } interface DepartmentInterface { generateReports(): void; } class AccountingDepartment extends Department implements DepartmentInterface { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10 a.m"); } generateReports(): void { console.log("Generating accounting reports..."); } }

To extract an interface

  1. Place the cursor anywhere inside the class from which you want to extract an interface.
  2. Choose Refactor | Extract | Interface on the main menu or on the context menu. The Extract Interface dialog opens.
  3. Specify the name of the new interface and select the checkboxes next to the class members you want to include in it.
  4. 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.
  5. Choose Extract Interface. WebStorm 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. WebStorm shows the proposed changes in the Refactoring Preview pane of the Find tool window. Note that if an instance references a method or a field that is not defined in the interface, WebStorm will not suggest replacing it.

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.

function Multiplication(a : number, b : number) { let с = a + b; let d = (с) * (с); return d; }
function Multiplication(a : number, b : number) { let d = ((a + b)) * ((a + b)); return d; }

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().

function Sum(a: number, b: number) { return a + b; } function Multiplication(a: number, b: number) { let d = Sum(a, b) * Sum(a, b); return d; } var e = Multiplication(4, 6);
function Multiplication(a : number, b : number) { let d = (a + b) * (a + b); return d; } var e = Multiplication(4, 6);

To run an Inline refactoring:

  1. In the editor, place the cursor at the symbol to be inlined and press Ctrl+Alt+N or choose Refactor | Inline on the context menu or on the main menu.
  2. In the Inline dialog box that corresponds to the selected symbol, confirm the inline refactoring.
    ws_ts_extract_variable.png

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.

In the example below, the function eat() is renamed to feed() and a new boolean parameter isMammal is introduced.

class Animal { constructor(age: number, name: string){ } eat(food: string[]): void { } } let Max = new Animal(23, 'Max'); Max.eat(['Apple', 'Parsley']); let Daisy = new Animal(12, 'Daisy'); Daisy.eat(['Pork', 'Fish']);
class Animal { constructor(age: number, name: string){ } feed(food: string[], isMammal: boolean = true): void { } } let Max = new Animal(23, 'Max'); Max.feed(['Apple', 'Parsley'], false); let Daisy = new Animal(12, 'Daisy'); Daisy.feed(['Pork', 'Fish'], false);

To invoke Change Signature
In the editor, place the cursor within the name of the function to refactor and press Ctrl+F6 or choose Refactor | Change Signature on the context menu or on the main menu. The Change Signature dialog opens.

To rename a function
In the Change Signature dialog (Ctrl+F6), edit the Name field.

To 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.

To change the visibility of a function
From the Visibility drop-down list, choose a function modifier, the available options are public (default), private, and protected,

To manage the function parameters
In the Change Signature dialog (Ctrl+F6), use the table of parameters and the buttons to the right of it:

  • To add a parameter, click new (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.
  • To remove a parameter, click any of the cells in the corresponding row and click delete (Alt+Delete).
  • To reorder the parameters, so required parameters are listed before optional ones, use arrowUp (Alt+Up) and arrowDown (Alt+Down). Learn more about required and optional parameters from the TypeScript Official website.
  • To rename a parameter, edit the Name field.

To propagate a parameter along the hierarchy of calls

  1. In the Change Signature dialog (Ctrl+F6), select the parameter and click propagateParameters. 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.
  2. In the left-hand pane, select the checkboxes next to the functions where you want to propagate the parameter and click OK.

To preview the changes and complete the refactoring

  1. In the Change Signature dialog (Ctrl+F6), click Preview.
  2. In the Refactoring Preview tab of the Find tool window, view the expected changes, make the necessary adjustments, and click Do Refactor when ready.

Last modified: 5 December 2017

See Also