Как скомпилировать typescript в javascript
Перейти к содержимому

Как скомпилировать typescript в javascript

  • автор:

Compiling TypeScript

TypeScript is a typed superset of JavaScript that transpiles 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:

You can test your install by checking the version or help.

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.

Compiler versus language service

It is important to keep in mind that VS Code’s TypeScript language service is separate from your installed TypeScript compiler. You can see the VS Code’s TypeScript version in the Status Bar when you open a TypeScript file.

TypeScript version displayed in the Status Bar

Later in the article, we’ll discuss how you can change the version of TypeScript language service that VS Code uses.

tsconfig.json

Typically the first step in any new TypeScript project is to add a tsconfig.json file. A tsconfig.json file defines the TypeScript project settings, such as the compiler options and the files that should be included. To do this, open up the folder where you want to store your source and add a new file named tsconfig.json . Once in this file, IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.

tsconfig.json IntelliSense

A simple tsconfig.json looks like this for ES5, CommonJS modules and source maps:

Now when you create a .ts file as part of the project we will offer up rich editing experiences and syntax validation.

Transpile TypeScript into JavaScript

VS Code integrates with tsc through our integrated task runner. We can use this to transpile .ts files into .js files. Another benefit of using VS Code tasks is that you get integrated error and warning detection displayed in the Problems panel. Let’s walk through transpiling a simple TypeScript Hello World program.

Step 1: Create a simple TS file

Open VS Code on an empty folder and create a helloworld.ts file, place the following code in that file.

To test that you have the TypeScript compiler tsc installed correctly and a working Hello World program, open a terminal and type tsc helloworld.ts . You can use the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) directly in VS Code.

You should now see the transpiled helloworld.js JavaScript file, which you can run if you have Node.js installed, by typing node helloworld.js .

build and run Hello World

Step 2: Run the TypeScript build

Execute Run Build Task ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ) from the global Terminal menu. If you created a tsconfig.json file in the earlier section, this should present the following picker:

TypeScript Build

Select the tsc: build entry. This will produce a HelloWorld.js and HelloWorld.js.map file in the workspace.

If you selected tsc: watch, the TypeScript compiler watches for changes to your TypeScript files and runs the transpiler on each change.

Under the covers, we run the TypeScript compiler as a task. The command we use is: tsc -p .

Step 3: Make the TypeScript Build the default

You can also define the TypeScript build task as the default build task so that it is executed directly when triggering Run Build Task ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ). To do so, select Configure Default Build Task from the global Terminal menu. This shows you a picker with the available build tasks. Select TypeScript tsc: build, which generates the following tasks.json file in a .vscode folder:

Notice that the task has a group JSON object that sets the task kind to build and makes it the default. Now when you select the Run Build Task command or press ( ⇧⌘B (Windows, Linux Ctrl+Shift+B ) ), you are not prompted to select a task and your compilation starts.

Tip: You can also run the program using VS Code’s Run/Debug feature. Details about running and debugging Node.js applications in VS Code can be found in the Node.js tutorial

Step 4: Reviewing build issues

The VS Code task system can also detect build issues through a problem matcher. A problem matcher parses build output based on the specific build tool and provides integrated issue display and navigation. VS Code ships with many problem matchers and $tsc seen above in tasks.json is the problem matcher for TypeScript compiler output.

As an example, if there was a simple error (extra ‘g’ in console.log ) in our TypeScript file, we may get the following output from tsc :

This would show up in the terminal panel ( ⌃` (Windows, Linux Ctrl+` ) ) and selecting the Tasks — build tsconfig.json in the terminal view dropdown.

You can see the error and warning counts in the Status Bar. Click on the error and warnings icon to get a list of the problems and navigate to them.

Error in Status Bar

You can also use the keyboard to open the list ⇧⌘M (Windows, Linux Ctrl+Shift+M ) .

Tip: Tasks offer rich support for many actions. Check the Tasks topic for more information on how to configure them.

JavaScript source map support

TypeScript debugging supports JavaScript source maps. To generate source maps for your TypeScript files, compile with the —sourcemap option or set the sourceMap property in the tsconfig.json file to true .

In-lined source maps (a source map where the content is stored as a data URL instead of a separate file) are also supported, although in-lined source is not yet supported.

Output location for generated files

Having the generated JavaScript file in the same folder at the TypeScript source will quickly get cluttered on larger projects. You can specify the output directory for the compiler with the outDir attribute.

Hiding derived JavaScript files

When you are working with TypeScript, you often don’t want to see generated JavaScript files in the File Explorer or in Search results. VS Code offers filtering capabilities with a files.exclude workspace setting and you can easily create an expression to hide those derived files:

This pattern will match on any JavaScript file ( **/*.js ) but only if a sibling TypeScript file with the same name is present. The File Explorer will no longer show derived resources for JavaScript if they are compiled to the same location.

Hiding derived resourcesHiding derived resources

Add the files.exclude setting with a filter in the workspace settings.json file, located in the .vscode folder at the root of the workspace. You can open the workspace settings.json via the Preferences: Open Workspace Settings (JSON) command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).

To exclude JavaScript files generated from both .ts and .tsx source files, use this expression:

This is a bit of a trick. The search glob pattern is used as a key. The settings above use two different glob patterns to provide two unique keys but the search will still match the same files.

Using newer TypeScript versions

VS Code ships with a recent stable version of the TypeScript language service and uses this by default to provide IntelliSense in your workspace. The workspace version of TypeScript is independent of the version of TypeScript you use to compile your *.ts files. You can just use VS Code’s built-in TypeScript version for IntelliSense without worry for most common cases, but sometimes you may need to change the version of TypeScript VS Code uses for IntelliSense.

Reasons for doing this include:

  • Trying out the latest TypeScript features by switching to the TypeScript nightly build ( typescript@next ).
  • Making sure you are using the same version of TypeScript for IntelliSense that you use to compile your code.

The active TypeScript version and its install location are displayed in the Status Bar when viewing a TypeScript file:

TypeScript status bar version

You have a few options if you want to change the default version of TypeScript in your workspace:

Using the workspace version of TypeScript

If your workspace has a specific TypeScript version, you can switch between the workspace version of TypeScript and the version that VS Code uses by default by opening a TypeScript or JavaScript file and clicking on the TypeScript version number in the Status Bar. A message box will appear asking you which version of TypeScript VS Code should use:

TypeScript version selector

Use this to switch between the version of TypeScript that comes with VS Code and the version of TypeScript in your workspace. You can also trigger the TypeScript version selector with the TypeScript: Select TypeScript Version command.

VS Code will automatically detect workspace versions of TypeScript that are installed under node_modules in the root of your workspace. You can also explicitly tell VS Code which version of TypeScript to use by configuring the typescript.tsdk in your user or workspace settings. The typescript.tsdk setting should point to a directory containing the TypeScript tsserver.js file. You can find the TypeScript installation location using npm list -g typescript . The tsserver.js file is usually in the lib folder.

Tip: To get a specific TypeScript version, specify @version during npm install. For example, for TypeScript 3.6.0, you would use npm install —save-dev typescript@3.6.0 . To preview the next version of TypeScript, run npm install —save-dev typescript@next .

Note that while typescript.tsdk points to the lib directory inside of typescript in these examples, the typescript directory must be a full TypeScript install that contains the TypeScript package.json file.

You can also tell VS Code to use a specific version of TypeScript in a particular workspace by adding a typescript.tsdk workspace setting pointing to the directory of the tsserver.js file:

The typescript.tsdk workspace setting only tells VS Code that a workspace version of TypeScript exists. To actually start using the workspace version for IntelliSense, you must run the TypeScript: Select TypeScript Version command and select the workspace version.

Using TypeScript nightly builds

The simplest way to try out the latest TypeScript features in VS Code is to install the JavaScript and TypeScript Nightly extension.

This extension automatically replaces VS Code’s built-in TypeScript version with the latest TypeScript nightly build. Just make sure you switch back to using VS Code’s TypeScript version if you’ve configured your TypeScript version with the TypeScript: Select TypeScript Version command.

Mixed TypeScript and JavaScript projects

It is possible to have mixed TypeScript and JavaScript projects. To enable JavaScript inside a TypeScript project, you can set the allowJs property to true in the tsconfig.json .

Tip: The tsc compiler does not detect the presence of a jsconfig.json file automatically. Use the –p argument to make tsc use your jsconfig.json file, e.g. tsc -p jsconfig.json .

Working with large projects

If you are working in a codebase with hundreds or thousands of TypeScript files, here are some steps you can take to improve both the editing experience in VS Code as well as compile times on the command line.

Make sure your tsconfig only includes files you care about

Use include or files in your project’s tsconfig.json to make sure the project only includes the files that should be part of the project.

More information on configuring your project’s tsconfig.json .

Break up your project using project references

Instead of structuring your source code as a single large project, you can improve performance by breaking it up into smaller projects using project references. This allows TypeScript to load just a subset of your codebase at a time, instead of loading the entire thing.

See the TypeScript documentation for details on how to use project references and best practices for working with them.

Next steps

Read on to find out about:

    — Specific editing features for TypeScript. — Useful refactorings from the TypeScript language service. — Configure the debugger for your TypeScript project.

Common questions

How do I resolve a TypeScript "Cannot compile external module" error?

If you get that error, resolve it by creating a tsconfig.json file in the root folder of your project. The tsconfig.json file lets you control how Visual Studio Code compiles your TypeScript code. For more information, see the tsconfig.json overview.

Why do I get different errors and warnings with VS Code than when I compile my TypeScript project?

VS Code ships with a recent stable version of the TypeScript language service and it may not match the version of TypeScript installed globally on your computer or locally in your workspace. For that reason, you may see differences between your compiler output and errors detected by the active TypeScript language service. See Using newer TypeScript versions for details on installing a matching TypeScript version.

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.

Why are some errors reported as warnings?

By default, VS Code TypeScript displays code style issues as warnings instead of errors. This applies to:

  • Variable is declared but never used
  • Property is declared but its value is never read
  • Unreachable code detected
  • Unused label
  • Fall through case in switch
  • Not all code paths return a value

Treating these as warnings is consistent with other tools, such as TSLint. These will still be displayed as errors when you run tsc from the command line.

Compiling TypeScript into JavaScript

Because browsers and Node.js process only JavaScript, you have to compile your TypeScript code before running or debugging it.

Compilation can also produce source maps that set correspondence between your TypeScript code and the JavaScript code that is actually executed.

WebStorm comes with a built-in TypeScript compiler. By default, it outputs generated JavaScript files and sourcemaps next to the TypeScript file.

Compilation is invoked with the Compile actions from the TypeScript widget on the Status toolbar as described in Compile TypeScript code below.

Compilation errors are reported in the TypeScript Tool Window. This list is not affected by changes you make to your code and is updated only when you invoke compilation again.

The tool window shows up only after you first compile your TypeScript code manually. After that the tool window is accessible via View | Tool Windows | TypeScript on the main menu or via the tool window bar.

Before you start

Press Ctrl+Alt+S to open the IDE settings and select Languages & Frameworks | TypeScript .

Make sure the TypeScript Language Service checkbox is selected.

Create and configure tsconfig.json files

By default, the built-in compiler does not create source maps that will let you step through your TypeScript code during a debugging session. The compiler also by default processes either the TypeScript file in the active editor tab or all TypeScript files from the current project.

With a tsconfig.json file, you can modify this default behavior to generate source maps and compile only files from a custom scope.

Create a tsconfig.json file

In the Project tool window, select the folder where your TypeScript code is (most often it is the project root folder) and then select New | tsconfig.json File from the context menu.

To generate source maps during compilation, make sure the sourceMap property is set to true .

To override the default compilation scope, which is the entire project, add the files property and type the names of the files to process in the following format:

Configure the scope for tsconfig.json

You may need to apply different TypeScript configurations to different files in your project.

It is not a problem if you arrange your sources so that all the files in each folder should be processed according to the same configuration. In such case you only have to create a separate tsconfig.json for each folder.

However if you want to apply different rules to the files that are stored in the same folder, you need to create several configuration files and configure scopes for them.

Create as many tsconfig*.json configuration files a s you need.

Open the Settings dialog ( Ctrl+Alt+S ), go to Editor | File Types , and make sure the names of all these files match the patterns from the Typescript config file name patterns list.

If necessary, add patterns as described in Add file type associations.

In each *tsconfig*.json , specify the files to be processed according to its settings:

List the file names explicitly in the files field:

In the include field, specify the file names or patterns:

To skip some files whose names match the patterns listed in the include field, list their names or patterns in the exclude field:

WebStorm doesn’t use just the nearest tsconfig.*.json (from the list of files recognized as Typescript config file type). @product@ uses the nearest tsconfig.*.json in which a particular file is somehow specified — either explicitly in the files field or through patterns in the include and exclude fields.

Compile TypeScript code

You can invoke compilation manually or have WebStorm compile your code automatically every time the code is changed.

Alternatively, you can configure a build process, for example, with webpack, babel, or another tool.

Manual compilation

Click the TypeScript widget on the Status bar.

The widget is shown on the Status bar all the time after you have opened a TypeScript file in the editor.

Select Compile , and then select one of the following options:

To compile the TypeScript code of the entire application, select Compile All .

Compile TypeScript code

Alternatively, select Compile TypeScript from the context menu of any open TypeScript file.

Compile TypeScript from context menu of a file

You can also press Ctrl+Shift+A and choose Compile TypeScript from the list.

To compile one file, open it in the editor, and select the path to the file from the list in the TypeScript widget.

To compile files from a custom scope, make sure they are listed in the files property of your tsconfig.json as described above. Click the TypeScript widget on the Status bar, select Compile , and then select the path to tsconfig.json .

Automatic compilation on changes

Open the Languages & Frameworks | TypeScript page of the IDE settings Ctrl+Alt+S and select the Recompile on changes checkbox.

Using TypeScript with Node.js: A Comprehensive Guide

Shahmeer

If you are working with Node.js, you might be familiar with the challenges of managing and scaling a large codebase. One way to overcome this is by using TypeScript, a statically-typed superset of JavaScript that adds optional type annotations and advanced features to the language. In this article, we will explore how to use TypeScript with Node.js, and provide examples to help you get started.

Table of Contents

  1. Introduction to TypeScript
  2. Setting up a TypeScript project
  3. Running TypeScript with Node.js
  4. Using TypeScript features in Node.js
  5. Debugging TypeScript code
  6. Using TypeScript with popular Node.js libraries
  7. Best practices for using TypeScript with Node.js
  8. Conclusion
  9. FAQs

Introduction to TypeScript

TypeScript is a language that provides static type checking for JavaScript. It was developed by Microsoft, and it is an open-source project that is widely adopted by the development community. With TypeScript, you can catch errors before runtime, improve code readability and maintainability, and use advanced features such as classes, interfaces, and enums. TypeScript is also compatible with popular JavaScript frameworks and libraries such as React, Angular, and Node.js.

Setting up a TypeScript project

To get started with TypeScript, you need to set up a project with the necessary dependencies and configuration. First, you need to install Node.js and npm on your machine. Then, you can create a new project directory and run the following command to initialize a new Node.js project:

This will create a package.json file in your project directory. Next, you need to install TypeScript as a development dependency:

After installing TypeScript, you need to create a tsconfig.json file in your project directory to specify the configuration options for TypeScript. Here is an example configuration:

In this configuration, we set the target ECMAScript version to ES6, specify the module format as CommonJS, set the output directory to dist , enable strict mode, enable interoperability with CommonJS modules, and skip checking external library files.

Running TypeScript with Node.js

After setting up a TypeScript project, you can use the TypeScript compiler ( tsc ) to compile your TypeScript code to JavaScript code that can be run by Node.js. You can run the compiler using the following command:

This will compile all TypeScript files in the src directory and output the compiled JavaScript files to the dist directory.

To run the compiled JavaScript files, you can use the node command followed by the path to the entry file. For example, if your entry file is dist/index.js , you can run it using the following command:

Using TypeScript features in Node.js

TypeScript provides advanced features such as classes, interfaces, and enums that can be used in Node.js applications. Here are some examples:

Classes

Interfaces

Enums

Debugging TypeScript code

When working with TypeScript, you might encounter errors that are not caught by the TypeScript compiler. To debug your TypeScript code, you can use the —inspect flag with the node command to start a debugging session. You can then use a debugger such as VS Code to set breakpoints and step through your code.

Using TypeScript with popular Node.js libraries

TypeScript is compatible with many popular Node.js libraries and frameworks. Here are some examples:

Express

TypeORM

Best practices for using TypeScript with Node.js

Here are some best practices for using TypeScript with Node.js:

  • Use strict mode to catch more errors at compile time.
  • Use interfaces and types to define the shape of your data and improve code readability.
  • Use tsconfig.json to specify the TypeScript configuration options for your project.
  • Use tools such as ESLint and Prettier to enforce code quality and consistency.

Use strict mode to catch more errors at compile time.

By enabling strict mode in TypeScript, you can catch potential errors and issues at compile time rather than at runtime. This can save you time and effort in the long run by avoiding hard-to-debug errors that may occur in production.

To enable strict mode, add "strict": true to your tsconfig.json file. This will enable a number of strict checks, such as:

  • Disallowing implicit any types
  • Enforcing null checks
  • Disallowing unused variables and imports

Use interfaces and types to define the shape of your data and improve code readability.

Using interfaces and types can help make your code more readable and maintainable by providing a clear definition of the shape of your data. This can also make it easier to catch type-related errors at compile time.

For example, consider the following code:

Using an interface to define the shape of the user object can make the code more readable:

Use tsconfig.json to specify the TypeScript configuration options for your project.

The tsconfig.json file is used to specify the TypeScript configuration options for your project. This can include things like:

  • The version of TypeScript to use
  • The root directory of your project
  • The output directory for compiled JavaScript files

By using a tsconfig.json file, you can easily share your TypeScript configuration with other developers and ensure consistency across your project.

Use tools such as ESLint and Prettier to enforce code quality and consistency.

ESLint and Prettier are both tools that can help enforce code quality and consistency in your TypeScript codebase. ESLint can be used to catch common errors and enforce coding standards, while Prettier can be used to automatically format your code to a consistent style.

By using these tools, you can help ensure that your code is maintainable and consistent across your project.

Изучаем TypeScript за 30 минут

Эта статья предназначена для людей, которые хорошо знают JavaScript, но мало знакомы с TypeScript. Мы рассмотрим большую часть основных функций, снабдив их примерами с комментариями.

Изучаем TypeScript за 30 минут

Преимущества TypeScript

JavaScript довольно неплохой язык программирования и вы можете задаться вопросом: «Действительно ли мне нужен TypeScript»? Технически, вам не нужно изучать его, чтобы быть хорошим разработчиком. Тем не менее, работа с TypeScript имеет свои преимущества:

  • Благодаря статической типизации код, написанный в TypeScript более предсказуем и, как правило, легче в отладке.
  • Упрощает организацию базового кода для очень больших и сложных программ благодаря модулям, пространствам имен и мощной поддержке ООП.
  • Компиляция в TypeScript включает в себя этап перехода к JavaScript, который обнаруживает все ошибки до того, как код, их содержащий, выполнится.
  • Фреймворк Angular 2 написан на TypeScript и рекомендуется разработчикам к использованию в их проектах.

Последний пункт является самым важным. Angular 2 — один из наиболее популярных на сегодняшний день фреймворков и хотя разработчики при работе с ним могут использовать обычный JavaScript, большинство учебников и примеров написаны на TS. Angular 2 расширяет свое сообщество и, естественно, что все больше и больше людей будет изучать TypeScript.

Рост популярности TypeScript, данные из Google TrendsРост популярности TypeScript, данные из Google Trends

Установка TypeScript

Установка TypeScript

Для работы нам потребуется Node.js и npm для этого урока. С помощью команды ниже мы можем установить пакет TypeScript на глобальном уровне, что делает компилятор TS доступным во всех наших проектах:

Попробуйте открыть терминал в любом месте и наберите tsc -v чтобы убедиться, что npm правильно установлено.

Текстовые редакторы с поддержкой TypeScript

Текстовые редакторы поддержкой TypeScript

TypeScript — проект с открытым исходным кодом, но разработан корпорацией Microsoft и изначально поддерживался лишь в платформе Visual Studio. В настоящее время существует масса текстовых редакторов и IDE, которые либо изначально, либо через плагины предлагают поддержку синтаксиса TypeScript, предложения автозаполнения, перехват ошибок и даже встроенные в компиляторы.

  • Visual Studio Code – легкий, с открытым исходным кодом редактор от Microsoft со встроенной поддержкой TypeScript.
  • Плагин для редактора Sublime Text .
  • Последняя версия WebStorm обладает встроенной поддержкой TypeScript.
  • Прочие , включая Vim, Atom, Emacs.

Компиляция TypeScript в JavaScript

Компиляция TypeScript в JavaScript

TypeScript записывается в .ts файлы (или .tsx для JSX), которые не могут быть использованы непосредственно в браузере и должны быть переведены в vanilla .js. Этот процесс компиляции может быть сделан следующими способами:

  • В терминале, используя ранее упомянутый инструмент командной строки tsc .
  • Непосредственно в Visual Studio, IDE и других текстовых редакторах.
  • Используя автоматизированные таск раннеры, например gulp.

Первый способ нам показался самым простым, поэтому мы и будем использовать его в нашем уроке. Команда, представленная ниже, принимает TypeScript-файл по имени main.ts и переводит его в JavaScript-версию: main.js . Если main.js существует, — он будет перезаписан.

Мы также можем собрать несколько файлов одновременно, перечислив все из них, или применив символы подстановки:

Мы можем также использовать опцию —watch , чтобы автоматически скомпилировать TypeScript-файл, когда сделаны изменения:

Более продвинутые пользователи могут также создавать файл конфигурации tsconfig.json, состоящий из различных параметров сборки. Файл конфигурации очень удобен при работе над крупными проектами с большим количеством .ts-файлов так как он несколько автоматизирует процесс. Подробнее о файле конфигурации можно узнать в документации по tsconfig.json .

Статическая типизация

Статическая типизация

Отличительной особенностью TypeScript является поддержка статической типизации. Это означает, что вы можете объявлять типы переменных и компилятор будет проверять правильность типов значений. Если объявления типа опущены, они будут автоматически определены из вашего кода. Любая переменная, аргумент функции или возвращаемое значение может иметь свой тип, определенный при инициализации:

Поскольку TypeScript компилируется в JavaScript, который не имеет ни малейшего представления о типах данных, они будут полностью удалены:

Однако, если мы попробуем сделать что-то неправильное, попытка компиляции tsc выдаст предупреждение об ошибке в коде. Например:

main.ts(1,5): error TS2322: Тип ‘Строка’ не может быть назначен для типа ‘Логическое значение’.

Он также предупреждает нас, если мы передаем неправильный аргумент функции:

main.ts(5,30): error TS2345: Argument of type ‘string’ is not assignable to parameter of type ‘number’. (ошибка TS2345: Аргумент типа ‘string’ не может быть присвоен параметру типа ‘number’.)

Вот некоторые из наиболее часто используемых типов данных:

  • Number – Любые числовые значения представлены числовым типом. И нет никаких отдельных определений для целочисленных, дробных и прочих переменных.
  • String – строки, таклй же текстовый тип как и в JavaScript, может быть окружен ‘ (одинарные кавычки), или » (двойные кавычки).
  • Boolean – логическое значение true , или false . Использование 0 , или 1 вызовет ошибку компиляции.
  • Any – · Any – Такая переменная может иметь такой тип, как String, Number, или что-либо другое.
  • Arrays – массивы, имеют два возможных синтаксиса: my_arr: number[]; , или my_arr: Array<number> .
  • Void – Используется для функций, которые ничего не возвращают.

Чтобы увидеть список всех доступных типов, перейдите на официальную документацию по TypeScript .

Интерфейсы

Интерфейсы

Интерфейсы используются для того, чтобы проверить, подходят ли объекты под ту или иную структуру. С их помощью можно выделять целые комбинации переменных, которые точно будут использоваться вместе друг с другом. При переводе на JavaScript интерфейсы исчезают — их единственная цель состоит в том, чтобы помочь в стадии разработки.

В приведенном ниже примере мы определяем простой интерфейс, который проверит аргументы функции:

Порядок свойств НЕ ИМЕЕТ значения, нужно лишь, чтобы они были верного типа. Если что-то отсутствует, имеет неправильный тип, или называется по-другому, — компилятор предупредит нас.

main.ts(16,7): error TS2345: Argument of type ‘ < nmae: string; calories: number; >is not assignable to parameter of type ‘Food’. Property ‘name’ is missing in type ‘< nmae: string; calories: number; >‘. ошибка TS2345: Аргумент типа ‘ < nmae: строка; calories: число; >не может быть присвоен параметру типа ‘Food’. Свойство ‘name’ не найдено в типе ‘< nmae: string; calories: number; >‘.

Поскольку это руководство для начинающих, мы не будем углубляться в интерфейсы. Тем не менее, если вы хотите побольше узнать о них, загдяните в документацию по интерфейсам .

Классы

Классы в TypeScript

При создании крупномасштабных приложений, объектно-ориентированный стиль программирования является предпочтительным для многими разработчиков, особенно в таких языках, как Java или C#. TypeScript предлагает систему классов, которая очень похожа на ту, что используется в этих языках, в том числе наследование, абстрактные классы, реализации интерфейса, сеттеры/геттеры и многое другое.

Также стоит отметить, что с последнего обновления JavaScript (ECMAScript 2015), классы являются родными для vanilla JS и могут быть использована без TypeScript. Две эти реализации очень похожи, но имеют некоторые отличия.

Продолжая тему еды напишем простой класс на TypeScript:

Тот, кто работал с Java или C# заметит, что синтаксисы довольно похожи. То же самое касается наследования:

Для получения более подробной информации советуем вам изучить документацию по классам в TS .

Generics

generics

Generics – это шаблоны, позволяющие одной и той же функции принимать аргументы разных типов. Лучше создавать компоненты в Generics, чем использовать тип данных any т.к. Generics сохраняет типы переменных, проходящих через него.

Простым примером мог бы стать скрипт, который получает аргумент и выводит массив, в котором он содержится.

Вызвав функцию в первый раз, мы вручную задали ей тип string (строка). Это не обязательная процедура, т.к. компилятор сам видит, какой аргумент передан, и может автоматически решить, какой тип ему лучше подходит, как и при втором вызове. Хотя это и не обязательно, но лучше каждый раз задавать тип самостоятельно, чтобы избежать возможных ошибок компилятора.

Документация по TypeScript включает в себя несколько продвинутых примеров, включая классы Generics, совмещая их с интерфейсами, а также многое другое. Вы можете прочитать об этом здесь .

Модули в TypeScript

Модули в TypeScript

Другим важным понятием при работе над большими приложениями является модульность. Разделение кода на множество мелких, повторно используемых компонентов помогает вашему проекту оставаться организованным и понятным, по сравнению одним файлом в 10000 строк.

TypeScript вводит синтаксис для экспорта и импорта модулей, но но не может обрабатывать связи между файлами. Для подключения внешних модулей TS полагается на сторонние библиотеки: require.js для браузерных приложений и CommonJS для Node.js. Давайте рассмотрим простой пример TypeScript-модулей с require.js:

У нас будет два файла. Один экспортирует функцию, а другой импортирует и вызывает ее.

exporter.ts
importer.ts

Теперь нам нужно скачать require.js и подключить его через тег script. Последний шаг состоит в компиляции двух файлов .ts. Необходимо добавить дополнительный параметр, чтобы TypeScript знал, что мы создаем модули для require.js (называемый также AMD), в отличие от CommonJS.

Модули являются довольно сложными для восприятия и выходят за рамки данного руководства. Если вы хотите, чтобы продолжить чтение о них, воспользуйтесь документацией о модулях .

Сторонние объявляющие файлы

9_declaration_files

При использовании библиотеки, которая была первоначально разработана для обычного JavaScript, нам нужно применить объявляющий файл, чтобы библиотека была совместима с TypeScript. Объявляющий файл имеет расширение .d.ts и содержит различную информацию о библиотеке и ее API.

Объявляющие файлы TypeScript обычно набираются вручную, но высока вероятность того, что нужная вам библиотека имеет файл с расширением .d.ts., созданный кем-то другим. DefinitelyTyped самое большое публичное хранилище файлов для различных библиотек. Существует также популярный Node.js-модуль для управления определениями TypeScript, которые называются Typings .

Если вам все еще нужно написать declaration file самостоятельно, то это руководство поможет вам начать работу.

Заключение

Мы надеемся, что вам понравился этот урок! Изучайте TypeScript и устраивайтесь на более высокооплачиваемую работу!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *