УСТАНОВКА TYPESCRIPT В VISUAL STUDIO CODE
TypeScript это полностью совместимый язык с JavaScript. Это означает что вы можете взять код на JavaScript, и он будет полностью валидный в любой среде TypeScript. Но помимо стандартного JavaScript, TypeScript – это мощный экзоскелет JavaScript-а.


Настройка среды
Есть несколько способов как работать с TypeScript. Сам TS (сокращенно от TypeScript) это препроцессор поэтому мы должны поставить какую-нибудь среду для работы с ним.
- Самый простой способ «поиграться с typescript» — это перейти на сайтwww.typescriptlang.org/play/

2. Способ второй можно скачать абсолютно беспутную и мощную IDE ( intelligent development environment ) от Microsoft по ссылке https :// www . visualstudio . com / ru / название IDE — Visual Studio Community 2017 при этом TS плагин уже встроен в неё. Если вы уже пользуетесь например VS 2015 и плагина для работы с TS еще нет, то скачать его можно по ссылке под видеоhttps://www.microsoft.com/ru-ru/download/details.aspx?id=48593 или наберите в поисковой строке google -а «typescript for visual studio»
3. Способ третий можно использовать любой редактор кода. Обычно редакторы проще IDE и весят меньше, да и почти не нагружают вашу систему, поэтому редакторы иногда использовать удобнее. Я рекомендую использовать еще один мощный и бесплатный продукт опять же от Microsoft, который называется visual studio code. Данный редактор кроссплатформенный и доступен как для мак так и для линукс. Хорошо, что Бил Гейтс ушел на пенсию, друзья. Это побудило MS изменить политику в опенсорсную сторону. Ссылка для скачивания:https://code.visualstudio.com/ также найдете под видео. Установите visual studio code как обычно.
После установки откройте редактор visual studio code и перейдите во вкладку File-> open folder. В открывшемся диалоговом окне выберите расположение будущей папки и создайте её. Например, с именем “Test”, после чего нажмите ок.
В обозревателе решения наведите на папку Test и нажмите на иконку добавить файл.

Добавьте два файла index . html и App . ts ( app это сокращение от слова application )
Давайте сделаем красивую тему для файлов. (Внимание — это пункт вы можете пропустить.)
Мне не нравится бедный стиль фалов, которые выглядят сейчас довольно скучно. Давайте изменим стиль отображения файлов в обозревателе решения.
Для этого нажмите сочетание клавиш shift + ctrl + p и напечатайте “ icon ”

Обратите внимание из списка настроек мы видим надпись « Preferences : File Icon Theme »
Выберите этот пункт и нажмите “ enter ”. Появится еще один список где вы можете видеть доступные темы для файлов. Я люблю тему “ Seti ( Visual Studio Code )” – минимально и симпатично. Выберите её и нажмите “ enter ”.

Обратите внимание как преобразовались значки, стало намного интереснее, теперь видны цветные обозначения типов. Если темы из списка Вам не нравятся, то вы можете выбрать любую доступную тему, сделанную сообществом.
Другой способ установить тему, более консервативный. Нажмите на File-> References -> settings

Появятся два окна слева предопределенные настройки самого редактора, а справа окно где вы можете перезаписать эти стандартные настройки. Поэтому просто добавьте строчку кода
TypeScript tutorial in Visual Studio Code
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
Install the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
npm install -g typescript
You can test your install by checking the version.
tsc --version
Hello World
Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.
mkdir HelloWorld cd HelloWorld code .
From the File Explorer, create a new file called helloworld.ts .

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.
let message: string = 'Hello World'; console.log(message);
To compile your TypeScript code, you can open the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) and type tsc helloworld.ts . This will compile and create a new helloworld.js JavaScript file.

If you have Node.js installed, you can run node helloworld.js .

If you open helloworld.js , you’ll see that it doesn’t look very different from helloworld.ts . The type information has been removed and let is now var .
var message = 'Hello World'; console.log(message);
IntelliSense
In VS Code, you can see that you get language features such as syntax highlighting and bracket matching. When you were typing in the editor, you may have noticed IntelliSense, the smart code completions and suggestions provided by VS Code and the TypeScript language server. Below you can see the methods of console

When you select a method, you then get parameter help and can always get hover information.

tsconfig.json
So far in this tutorial, you have been relying on the TypeScript compiler’s default behavior to compile your TypeScript source code. You can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.
Important: To use tsconfig.json for the rest of this tutorial, invoke tsc without input files. The TypeScript compiler knows to look at your tsconfig.json for project settings and compiler options.
Add a simple tsconfig.json that set the options to compile to ES5 and use CommonJS modules.
"compilerOptions": "target": "es5", "module": "commonjs" > >
When editing tsconfig.json , IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.

By default, TypeScript includes all the .ts files in the current folder and subfolders if the files attribute isn’t included, so we don’t need to list helloworld.ts explicitly.
Change the build output
Having the generated JavaScript file in the same folder as the TypeScript source will quickly get cluttered on larger projects, so you can specify the output directory for the compiler with the outDir attribute.
"compilerOptions": "target": "es5", "module": "commonjs", "outDir": "out" > >
Delete helloworld.js and run the command tsc with no options. You will see that helloworld.js is now placed in the out directory.
See Compiling TypeScript to learn about other features of the TypeScript language service and how to use tasks to run your builds directly from VS Code.
Error checking
TypeScript helps you avoid common programming mistakes through strong type checking. For example, if you assign a number to message , the TypeScript compiler will complain with ‘error TS2322: Type ‘2’ is not assignable to type ‘string’. You can see type checking errors in VS Code both in the editor (red squiggles with hover information) and the Problems panel ( ⇧⌘M (Windows, Linux Ctrl+Shift+M ) ). The [ts] prefix lets you know this error is coming from the TypeScript language service.

Quick Fixes
The TypeScript language service has a powerful set of diagnostics to find common coding issues. For example, it can analyze your source code and detect unreachable code which is displayed as dimmed in the editor. If you hover over the line of source code, you’ll see a hover explaining and if you place your cursor on the line, you’ll get a Quick Fix light bulb.

Clicking on the light bulb or pressing ⌘. (Windows, Linux Ctrl+. ) brings up the Quick Fix menu where you can select the Remove unreachable code fix.
Debugging
VS Code has built-in support for TypeScript debugging. To support debugging TypeScript in combination with the executing JavaScript code, VS Code relies on source maps for the debugger to map between the original TypeScript source code and the running JavaScript. You can create source maps during the build by setting «sourceMap»: true in your tsconfig.json .
"compilerOptions": "target": "es5", "module": "commonjs", "outDir": "out", "sourceMap": true > >
Rebuild by running tsc and you should now have a helloworld.js.map in the out directory next to helloworld.js .
With helloworld.ts open in the editor, press F5 . If you have other debugger extensions installed, you need to select Node.js from the dropdown.
The debugger will start a session, run your code, and display the «Hello World» message in the Debug console panel.

In helloworld.ts , set a breakpoint by clicking on the left gutter of the editor. You will see a red circle if the breakpoint is set. Press F5 again. Execution will stop when the breakpoint is hit and you’ll be able to see debugging information such as variable values and the call stack in the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ).

See Debugging TypeScript to learn more about VS Code’s built-in debugging support for TypeScript and how you can configure the debugger for your project scenarios.
Next steps
This tutorial was a quick introduction to using VS Code for TypeScript development. Read on to learn more about using VS Code’s compiling and debugging support for TypeScript:
- Compiling TypeScript — Use VS Code’s powerful task system for compiling TypeScript.
- Editing TypeScript — Specific editing features for TypeScript.
- Refactoring TypeScript — Useful refactorings from the TypeScript language service.
- Debugging TypeScript — Configure the debugger for your TypeScript project.
Common questions
Cannot launch program because corresponding JavaScript cannot be found
You’ve likely not set «sourceMap»: true in your tsconfig.json and the VS Code Node.js debugger can’t map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.
TypeScript in Visual Studio Code
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.

Installing the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
npm install -g typescript
You can test your install by checking the version.
tsc --version
Another option is to install the TypeScript compiler locally in your project ( npm install —save-dev typescript ) and has the benefit of avoiding possible interactions with other TypeScript projects you may have.
Hello World
Let’s start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.
mkdir HelloWorld cd HelloWorld code .
From the File Explorer, create a new file called helloworld.ts .

Now add the following TypeScript code. You’ll notice the TypeScript keyword let and the string type declaration.
let message: string = 'Hello World'; console.log(message);
To compile your TypeScript code, you can open the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) and type tsc helloworld.ts . This will compile and create a new helloworld.js JavaScript file.

If you have Node.js installed, you can run node helloworld.js .

If you open helloworld.js , you’ll see that it doesn’t look very different from helloworld.ts . The type information has been removed and let is now var .
var message = 'Hello World'; console.log(message);
IntelliSense
IntelliSense shows you intelligent code completion, hover information, and signature help so that you can write code more quickly and correctly.

VS Code provides IntelliSense for individual TypeScript files as well as TypeScript tsconfig.json projects.
Hover information
Hover over a TypeScript symbol to quickly see its type information and relevant documentation:

You can also show the hover information at the current cursor position with the ⌘K ⌘I (Windows, Linux Ctrl+K Ctrl+I ) keyboard shortcut.
Signature help
As you write a TypeScript function call, VS Code shows information about the function signature and highlights the parameter that you are currently completing:

Signature help is shown automatically when you type a ( or , within a function call. Use ⇧⌘Space (Windows, Linux Ctrl+Shift+Space ) to manually trigger signature help.
Snippets
In addition to smart code completions, VS Code also includes basic TypeScript snippets that are suggested as you type.

You can install extensions to get additional snippets or define your own snippets for TypeScript. See User Defined Snippets for more information.
Tip: You can disable snippets by setting editor.snippetSuggestions to «none» in your settings file. If you’d like to see snippets, you can specify the order relative to suggestions; at the top ( «top» ), at the bottom ( «bottom» ), or inlined ordered alphabetically ( «inline» ). The default is «inline» .
Errors and warnings
The TypeScript language service will analyze your program for coding problems and report errors and warnings:
- In the Status bar, there is a summary of all errors and warnings counts.
- You can click on the summary or press ⇧⌘M (Windows, Linux Ctrl+Shift+M ) to display the PROBLEMS panel with a list of all current errors.
- If you open a file that has errors or warnings, they will be rendered inline with the text and in the overview ruler.

To loop through errors or warnings in the current file, you can press F8 or ⇧F8 (Windows, Linux Shift+F8 ) which will show an inline zone detailing the problem and possible Code Actions (if available):

Code navigation
Code navigation lets you quickly navigate TypeScript projects.
- Go to Definition F12 — Go to the source code of a symbol definition.
- Peek Definition ⌥F12 (Windows Alt+F12 , Linux Ctrl+Shift+F10 ) — Bring up a Peek window that shows the definition of a symbol.
- Go to References ⇧F12 (Windows, Linux Shift+F12 ) — Show all references to a symbol.
- Go to Type Definition — Go to the type that defines a symbol. For an instance of a class, this will reveal the class itself instead of where the instance is defined.
- Go to Implementation ⌘F12 (Windows, Linux Ctrl+F12 ) — Go to the implementations of an interface or abstract method.
You can navigate via symbol search using the Go to Symbol commands from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
- Go to Symbol in File ⇧⌘O (Windows, Linux Ctrl+Shift+O )
- Go to Symbol in Workspace ⌘T (Windows, Linux Ctrl+T )
Formatting
VS Code includes a TypeScript formatter that provides basic code formatting with reasonable defaults.
Use the typescript.format.* settings to configure the built-in formatter, such as making braces appear on their own line. Or, if the built-in formatter is getting in the way, set «typescript.format.enable» to false to disable it.
For more specialized code formatting styles, try installing one of the formatting extensions from the VS Code Marketplace.
Refactoring
VS Code includes some handy refactorings for TypeScript such as Extract function and Extract constant. Just select the source code you’d like to extract and then click on the light bulb in the gutter or press ( ⌘. (Windows, Linux Ctrl+. ) ) to see available refactorings.

See Refactoring TypeScript for more information about refactorings and how you can configure keyboard shortcuts for individual refactorings.
Rename
One of the simplest refactorings is to rename a method or variable. Press F2 to rename the symbol under the cursor across your TypeScript project:

Debugging
VS Code comes with great debugging support for TypeScript, including support for sourcemaps. Set breakpoints, inspect objects, navigate the call stack, and execute code in the Debug Console. See Debugging TypeScript and the overall Debugging topic to learn more.
Debug client side
You can debug your client-side code using a browser debugger such as the built-in Edge and Chrome debugger, or the Debugger for Firefox.
Debug server side
Debug Node.js in VS Code using the built-in debugger. Setup is easy and there is a Node.js debugging tutorial to help you.
Linters
Linters provides warnings for suspicious looking code. While VS Code does not include a built-in TypeScript linter, TypeScript linter extensions available in the Marketplace.
ESLint is a popular linter, which also supports TypeScript. The ESLint extension integrates ESLint into VS Code so you can see linting errors right in the editor and even quickly fix many of them with Quick Fixes. The ESLint plugin guide details how to configure ESLint for your TypeScript projects.
TypeScript extensions
VS Code provides many features for TypeScript out of the box. In addition to what comes built-in, you can install an extension for greater functionality.
Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
Next steps
To learn more, see:
- TypeScript tutorial — Create a simple Hello World TypeScript in VS Code.
- Editing TypeScript — Specific editing features for TypeScript.
- Refactoring TypeScript — Useful refactorings from the TypeScript language service.
- Compiling TypeScript — Compile TypeScript to a JavaScript target version.
- Debugging TypeScript — Learn about debugging TypeScript both server and client-side with VS Code.
Common questions
Can I use the version of TypeScript that ships with VS 2022?
No, the TypeScript language service that ships with Visual Studio 2019 and 2022 isn’t compatible with VS Code. You will need to install a separate version of TypeScript from npm.
How can I use the latest TypeScript beta with VS Code?
The simplest way to try out the latest TypeScript features in VS Code is to install the JavaScript and TypeScript Nightly extension.
Как установить typescript в visual studio code
Если у вас не установлена Visual Studio Code нужно установить Visual Studio Code .
Открываем Visual Studio Code

Делаем чтобы файл автоматически сохранялся в Visual Studio Code .

Шаг 2. Создаем новую папку my_typescript_project1 на диске D: и в Visual Studio Code выбираем эту папку
Создаем новую папку my_typescript_project1 на диске D: и
в Visual Studio Code нажимаем
File → Open Folder .
и выбираем эту папку D:/my_typescript_project1

Шаг 3. Создаем новый файл index.html внутри Visual Studio Code

Добавим код в
Файл index.html
Сохраним файл для этого нажимаем File → Save

Шаг 4. В терминальной строке выполним npm init для создания файла package.json
Откроем терминальную строку:
Нажимаем Terminal → New Terminal

Все время нажимаем кнопку Enter

Результат: создался файл package.json
Добавим скрит MyBuild в файл package.json
Файл D:/my_typescript_project1/ package.json
<
«name» : «my_typescript_project1» ,
«version» : «1.0.0» ,
«description» : «»,
«main» : «index.js» ,
«scripts» : <
«MyBuild» : «tsc»
>,
«author» : «»,
«license» : «ISC» ,
«devDependencies» : <
«typescript» : «^3.9.7»
>
>
Скрипт MyBuild будет запускать tsc
tsc это программа TypeScript которая конвертирует ts файл в js файл
Запуск tsc без параметров означает что настройки будут браться из файла tsconfig.json
Читайте подробнее о npm скриптах .
Шаг 5. В терминальной строке выполним npm install —save-dev typescript для установки пакета TypeScript
npm install —save-dev typescript

Шаг 6. Создаем новый файл tsconfig.json внутри Visual Studio Code для конвертации файла ts в файл js

Добавим код в
Файл tsconfig.json
<
«compilerOptions» : <
«module» : «commonjs» ,
«target» : «es6» ,
«lib» : [ «es6» ],
«sourceMap» : true, // true means that will be generating debug information(map file). And you can debug application with breakpoints.
«outDir» : «./build»
>,
«exclude» : [
«node_modules»
]
>
Сохраним файл для этого нажимаем File → Save
Шаг 7. Создаем новый файл src/my.ts внутри Visual Studio Code

Добавим код в
файл src/my.ts
class Book
<
public Name: string ;
constructor ()
<
this .Name = «Good book» ;
>
>
Сохраним файл для этого нажимаем File → Save
Шаг 8. Создаем новый файл .vscode/launch.json внутри Visual Studio Code

Добавим код в
Файл .vscode/ launch.json
<
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
«version» : «0.2.0» ,
«configurations» : [
<
«type» : «chrome» ,
«request» : «launch» ,
«name» : «Launch Chrome» ,
«url» : «$/index.html»
>
]
>
Шаг 9. Компилируем проект (выполним npm run MyBuild для конвертации файла ts В js)
npm run MyBuild

Увидим что в папке build создался файл my.js
Шаг 10. Запускаем проект нажимаем Run → Start Debugging. Ошибка «Configured debug type ‘chrome’ is not supported»

Ошибка «Configured debug type ‘chrome’ is not supported»

Установим Chrome Debugger

Шаг 11. Запускаем проект в отладчике (для этого нажимаем Run → Start Debugging или клавиша F5)

На экране увидим результат:

Шаг 12. Ставим точки остановки (Breakpoints)
Поставим точки остановки в файле index.js
Точки остановки ставятся нажатием клавиши F9

Запускаем программу в отладчике (debug). Нажимаем Run → Run debugger или кнопку F5
Программа запущена и мы можем смотреть:
• WATCH (значение переменных)
• CALL STACK (стэк вызова функций)
• BREAKPOINTS (ставить, убирать точки остановки)

На заметку!
После нажатия клавиши F5 в первый раз отладчик не останавливается на точке остановки (breakpoints).
Отладчик заходит в точку остановки (breakpoints) когда я нажимаю Restart


Скачать пример

my_typescript_project1.zip .
размер: 2.7 kb
Структура файлов:
D:/my_typescript_project1
index.html
package.json файл настройки Node.js (содержит названия пакетов)
tsconfig.json файл настройки TypeScript (путь куда конвертировать js файл)
.vscode
launch.json файл настройки для Visual Studio Code (путь к запускаемому файлу)
src
my.ts
build
my.js появится этот файл когда скомпилируем проект
Смотрим файлы
Файл index.html
Файл package.json
<
«name» : «my_typescript_project1» ,
«version» : «1.0.0» ,
«description» : «»,
«main» : «index.js» ,
«scripts» : <
«MyBuild» : «tsc»
>,
«author» : «»,
«license» : «ISC» ,
«devDependencies» : <
«typescript» : «^3.9.7»
>
>
Файл tsconfig.json
<
«compilerOptions» : <
«module» : «commonjs» ,
«target» : «es6» ,
«lib» : [ «es6» ],
«sourceMap» : true, // true means that will be generating debug information(map file). And you can debug application with breakpoints.
«outDir» : «./build»
>,
«exclude» : [
«node_modules»
]
>
Файл .vscode/launch.json
<
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
«version» : «0.2.0» ,
«configurations» : [
<
«type» : «chrome» ,
«request» : «launch» ,
«name» : «Launch Chrome» ,
«url» : «$/index.html»
>
]
>
Файл src/my.ts
class Book
<
public Name: string ;
constructor ()
<
this .Name = «Good book» ;
>
>