انتقل إلى المحتوى الرئيسي

Declarations

Declarations are a very important part of TypeScript due to which static typing is projected onto dynamic JavaScript.

Declaration

Since the development of programs in TypeScript uses libraries written in JavaScript, the tsc compiler, whose main task is type checking, feels like it is blindfolded. Despite the fact that with each new version type inference is getting better and better at understanding JavaScript, it is still far from ideal. In addition, parsing the JavaScript code adds a load on the processor, which is sometimes not enough precious time when developing modern applications.

TypeScript solved this problem by connecting to the project the declarations it generated in advance or manually created by developers. Declarations are placed in files with the extension .d.ts and consist only of type declarations that completely repeat the program until the moment of compilation, when it was deprived of all typing features. Their operation is very similar to the operation of files with the extension .h in languages C/C++.

// Файл Animal.ts
export default class Animal {
public name: string = 'animal';
public voice(): void {}
}

// Файл Animal.d.ts
declare module "Animal" {
export default class Animal {
name: string;
voice(): void;
}
}

Installation declaration

If the declaration is distributed separately from the library, then it will most likely end up in a huge repository on github called DefinitelyTyped containing a huge number of declarations. To make it easier to navigate in this set, in addition to the site TypeSearch acting as a search engine, a declaration manager called Typed was created. But we will not talk about it since it is used when working with TypeScript versions less than v2.0, so we will talk about its development in the image of the package manager team npm, namely @types.

In order to set the required declaration, in the terminal it is necessary to execute the command, part of which consists of their directive @ types, followed by the name of the library, separated by a slash/.

npm i -D @types/name

Creating a declaration

In addition to the fact that the declaration can be written by hand, it can also be generated automatically, provided that the code is written in TypeScript. In order for tsc to generate declarations during compilation, you need to activate the compiler option --declaration.

It will not be superfluous to remind you that the declaration needs to be generated only when the library is completely ready. The entry point of the compiler itself is the configuration file that was installed for it at startup. This means that if the project is in the src directory, then in the declaration the path will be specified as src / libname instead of the required lib.

// Ожидается
declare module 'libname' {
// ...
}

// Есть
declare module 'src/libname' {
// ...
}

Example

Let's see how we can use header files, using the example of using global variables. For example, a JS variable is defined on a web page.

<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML</title>
</head>

<body>
<h1>TypeScript HTML</h1>
<div id="content"></div>
<script>
let gVar = 'Hello TypeSript !'
</script>
<script src="app.js"></script>
</body>
</html>

We want to access this variable in the TypeScript code in the file app.ts.

class Utility {
static displayGlobalVar() {
console.log(globalVar)
}
}

window.onload = () => {
Utility.displayGlobalVar()
}

When the application is launched, the TS compiler will not be able to compile the program, since the global variable does not yet exist for the TS code. In this case, we need to include the definition of a global variable using declarative files. To do this, add a new file to the project, which we will call globals.d.ts and which will have the following content.

declare let gVar: string

Using the declare keyword, the definition of a global variable is included in the TS program. Let's also change the file app.ts.

// <reference path="globals.d.ts" />

class Utility {
static displayGlobalVar() {
console.log(gVar)
}
}
window.onload = () => {
Utility.displayGlobalVar()
}

Using the reference directive at the beginning of the file, the header file globals.d.ts is included. The path parameter specifies the path to the header file.

Project structure:

  • app.ts
  • globals.d.ts
  • index.html

When you run the index.html file in the developer console, you will see the phrase Hello TypeScript !.

Questions

Now we are ready to explore with you TypeScript, but in order to understand how much you learned this lesson, take the test in the mobile application in our school on this topic.

EnglishMoji!

  1. TypeScriptLang
  2. Modules

Contributors ✨

Thanks goes to these wonderful people (emoji key):


IIo3iTiv


Dmitriy Vasilev

💵

EnglishMoji!