If you have experienced the convenience brought by a strongly typed language like JAVA, including its rich type variables, abstractions, and interfaces, you will definitely feel unsatisfied when you switch to JavaScript. Especially the variable Number declared by JavaScript can be easily assigned to String. How the IDE implements any type of IntelliSense is very confusing.
Faced with this technical obstacle, we cannot ignore the convenience brought by TypeScript. Compared with JavaScript, the most obvious point is that we can give the IDE the ability to actually use it. This article will introduce some TypeScript coding techniques to help you work more quickly and efficiently.
Create a custom code snippet
Obtaining the default code segment and custom code segment is an important part of VScode's IntelliSense function. The code slice can greatly reduce the time of writing code. You only need to remember to use the prefix and what trigger to use.
You can view it by selecting "Insert Code Snippet" from the command menu. The list is rich in content and can be of great help in daily work.
Another important content is to add custom code snippets.
How to use: Select "User Code Snippet" under "File"> "Preferences" ("Code"> "Preferences" on macOS), select the language that the code snippet can access, or the global language.
To add a custom code snippet, you only need to add a JSON definition in the file.
The new snippets file is created in the project folder with a custom extension and supports JSON inline comments.
The content that needs to be defined includes:
- Name, if there is no description, it will be part of the IntelliSense drop-down list
- Range, the default is the whole sentence code segment
- Prefix, as the word that triggers the fragment, can be defined as a string group or value
- The main body, contains a list of code lines, you can add VScode tags, and use TAB to move
- Description, this item is optional, if not used, the name of the item listed in the IntelliSense drop-down menu will be displayed when it appears
In the above example, we created a custom code snippet, which will be triggered when we start to write "mylog". Someone may have questions about the console.log in the code, but note that there is also a predefined variable: TM_SELECTED_TEXT, which refers to the currently selected text. Therefore, if we manually trigger this code segment when we select the code, it will encapsulate the selection in a console.log statement.
Here are some predefined variables of commonly used code segments in development:
- TM_SELECTED_TEXT currently selected text or empty string
- TM_CURRENT_LINE The contents of the current line
- TM_CURRENT_WORD The content of the word under the cursor or an empty string
- TM_LINE_INDEX line number based on zero index
- TM_LINE_NUMBER The line number based on an index
- TM_FILENAME The file name of the current document
- TM_FILENAME_BASE The file name of the current document, without extension
- TM_DIRECTORY The directory of the current file
- TM_FILEPATH The full file path of the current document
- CLIPBOARD clipboard contents
- WORKSPACE_NAME The name of the workspace or folder opened
Date and time quote:
- CURRENT_YEAR this year
- CURRENT_YEAR_SHORT The last two digits of the year
- CURRENT_MONTH Two-digit month (e.g. "02")
- Full name of CURRENT_MONTH_NAME month (e.g. "July")
- CURRENT_MONTH_NAME_SHORT Short name of the month (e.g. "July")
- CURRENT_DATE day of the month
- CURRENT_DAY_NAME The name of the day (e.g. "Monday")
- CURRENT_DAY_NAME_SHORT Short name for one day (e.g. "Mon")
- CURRENT_HOUR current hour (24-hour clock)
- CURRENT_MINUTE current minute
- CURRENT_SECOND current second
- CURRENT_SECONDS_UNIX The number of seconds since the Unix era
Dynamically add valid annotation tags:
- BLOCK_COMMENT_START output example: JavaScript/* or HTML<!--
- BLOCK_COMMENT_END output example: JavaScript*/or HTML-->
- LINE_COMMENT sample output: in JavaScript //
Give some examples to illustrate:
Through "doc", trigger the creation of a comment block, and the cursor is positioned at position $1. If you write content in it and press the TAB key, it will jump to position $2.
The final result is as follows:
Custom TypeScript format
Customize your own coding format according to your personal style and coding habits
In the setting window, type "typescript.formatting", TypeScript provides 24 formatting options.
The selectable range includes: adding spaces after opening and closing string brackets, adding brackets in a new line of the function, and handling semicolons (you can choose to ignore, add missing brackets or automatically delete them all).
Through this list, we can customize VSCode to make the code style more in line with personal coding habits. After completion, it will take effect by selecting the "Set Document Format" option on the command panel.
Easily reconfigurable
Refactoring on large code bases is particularly troublesome, and simple changes (for example, moving class definitions from one folder to another) can affect many files.
And VSCode provides a set of functions that are very easy to use and do not require any additional extensions.
1. Rename existing symbols
You can rename the variable or class name in the code through a simple Search&Replace, unless the name is part of other entities, such as naming the class Car, and then use oCar as an instance variable. If you only intend to rename the actual class, it will cause some problems.
VSCode simplifies a lot of work, all we have to do is select one of the entities to be renamed, and then press F2 (or right-click it and select "Rename Symbol", the operation of mac is a little different). Choose a new name, and everything used in the process (including definitions, if you didn't click on it initially) will be renamed correctly.
2. Abstract construction
If it is used more than once, it needs to be abstracted. A common reconstruction technique is to extract logic into a function or a method.
Abstract by selecting the code to be reused and clicking the light bulb next to it. For example, the following code needs to extract the last two lines:
Select the extraction to take effect in the global scope, enter the new function name, you will get the following:
At the same time, the countCharacters function needs some modification, and the benefits are obvious in more complex use cases.
The light bulb's menu options are context-aware. If we are using classes, we can also choose to extract the code as a new method, or convert the type to an interface, and convert a single value to a constant.
3. Simplify function signature
Excessive parameters are simplified by adding object decomposition to the mix:
Select all the parameters, then click the light bulb, select "Convert parameters to deformed objects"
Further optimization, open the type declaration, and then convert it to an external type, you can select the type definition again
Clicking "Extract to Type Alias" will ask for a new type name, which will create the name and place it on the signature of the function
Simplify this code further
Automatic operation after saving the file
We have all experienced the awkward situation of forgetting to format the file or running the linter before submitting the code to the repository. When using VSCode, we define the preset operation to be executed immediately after the file is saved, so as to avoid the development of Omission.
The setting process is to edit the settings.json file. Add editor.codeActionsOnSave to set the list of operations to be performed after saving the file, including operations such as running ESLint or adding missing imports.
It can be set to the following array:
“ editor.codeActionsOnSave”:[“ source.fixAll.eslint”,“ source.addMissingImports”]
At the same time, if we want to automatically add the aforementioned formatting options when saving the file (instead of manually formatting the document), we can add the following entry to our settings.json:
"editor.formatOnSave": true
For example, realize that the semicolon is set to be inserted automatically.
CodeLens counter
VSL does not activate CodeLens by default, which is very inconvenient for large code bases. Here are some refactoring ideas:
There is a small mark by enabling the function that lists the implementation and referenced counters of classes, functions, types, and other constructs.
To enable this feature, just look for the word "CodeLens" on the settings screen. Enable all counters.
You will get the following:
"3 references" and "1 reference" are directly added by VSCode. Once you click on them, you will get an expanded view of the code constructed by the reference (in this example, the defined type):
Extended reading
If you are proficient in TypeScript coding development skills and want to implement online design and data reporting of Excel reports in your Web projects, then you are welcome to download and try this pure front-end form control SpreadJS . ) Give us your product recommendations.
to sum up
These TypeScript coding techniques summarized in this article can effectively improve your coding efficiency. In the future, we will bring you more related techniques to help developers.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。