Типы на каждый день

Алан-э-Дейл       31.03.2024 г.

Введение в типизацию

 

React — инструмент, позволяющий создавать пользовательские интерфейсы, обеспечивать вывод на экраны данных, отображаемых на веб-страницах. За счет разбивки страниц на небольшие фрагменты, инструмент облегчает создание интерфейсов. Владилен Минин, автор курсов «Стань javascript Senior» Angular 9, React Native, ReactJS, NodeJS, Angular Fullstack, бесплатных видеоуроков на YouTube, раскрывает тему применения React JS + TS. Владилен покажет работу типизации, взяв за пример приложение, на базе написания которого разбираются наиболее значимые аспекты тематики. Дополнительно рассматривается @types + React Router DOM. Занятие пригодится людям, желающим подробнее разобраться в принципах, систематизировать имеющиеся отрывки знаний.

«Тайскрипт» «родился» в 2012 году с легкой подачи датчанина Андерса Хейлсберга, создавшего Turbo Pascal, Delphi, C#, за них он получил награду ежемесячного компьютерного журнала Dr. Dobb’s Journal в 2000 г. Последнее «детище» Хейлсберга набирает популярность за счет имеющихся преимуществ, но существуют базовые навыки – их постоянно стоит держать в уме. Например, не следует писать функции для передачи большого количества параметров, придется ввести в привычку необходимость группировать связанные переменные и функции, правильно использовать конструкторы, позволяющие задавать значения свойств.
 

— Урок javascript

— Уроки C++

— Уроки C

— Уроки Python

— Курсы программирования

10 марта 2021

It’s getting better all the time

TypeScript continues to evolve, with its 3.8 version coming soon. At the time of writing, the release candidate was already available, and the production release will come with the same set of upgrades plus some critical bug fixes. So, what major improvements does the fresh version bring?

New syntax for type-only imports and exports. This update is supposed to give developers more control over how the compiler imports and elides (omits) some elements.

Support for ECMAScript private fields. ECMAScript or ES for short is a specification that defines rules and guidelines for scripting languages, and it lies at the core of JS. In 2015, ES introduced the concept of a class to JavaScript — roughly, it’s a template that defines how the function of a certain type (or class) should behave.

By default, ES classes are public, which means they can be accessed and modified outside the class. The implementation of private fields — data slots, available from inside the class only — enables programmers to create a kind of protective cover, secluding internal details and preventing unwelcome interventions. This feature is already supported in Node.js 12, Chrome 74, and Babel.

“Fast and Loose” incremental checking. The new compiling option reveals if the file needs rechecking or rebuilding, based on changes made to it. The update is supposed to reduce build time and thus favor large projects.

Rest Parameters

Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type.

To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter.

Example: Rest Parameters

function addNumbers(...nums:number[]) {  
   var i;   
   var sum:number = 0; 
   
   for(i = 0;i<nums.length;i++) { 
      sum = sum + nums; 
   } 
   console.log("sum of the numbers",sum) 
} 
addNumbers(1,2,3) 
addNumbers(10,10,10,10,10)
  • The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter.

  • The function is invoked twice, by passing three and six values, respectively.

  • The for loop iterates through the argument list, passed to the function and calculates their sum.

On compiling, it will generate following JavaScript code −

function addNumbers() {
   var nums = [];
   for (var _i = 0; _i < arguments.length; _i++) {
      nums = arguments;
   }
	var i;
   var sum = 0;
	
   for (i = 0; i < nums.length; i++) {
      sum = sum + nums;
   }
   console.log("sum of the numbers", sum);
}
addNumbers(1, 2, 3);
addNumbers(10, 10, 10, 10, 10);

The output of the above code is as follows −

sum of numbers 6 
sum of numbers 50

TypeScript Features

  • Cross-Platform: TypeScript runs on any platform that JavaScript runs on.
    The TypeScript compiler can be installed on any Operating System such as Windows, macOS, and Linux.
  • Object-Oriented Language: TypeScript provides powerful features such as Classes, Interfaces, and Modules. You can write pure object-oriented code for client-side as well as server-side development.
  • Static type-checking: TypeScript uses static typing. This is done using type annotations. It helps type checking at compile time.
    Thus, you can find errors while typing the code without running your script each time. Additionally, using the type inference mechanism, if a variable is declared without a type, it will be inferred based on its value.
  • Optional Static Typing: TypeScript static typing is optional, if you prefer to use JavaScript’s dynamic typing.
  • DOM Manipulation: Like JavaScript, TypeScript can be used to manipulate the DOM.
  • ES 6 Features: TypeScript includes most features of planned ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions etc.

Features of TypeScript

TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution.

TypeScript supports other JS libraries. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries.

JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files.

TypeScript is portable. TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute.

TypeScript and ECMAScript

The ECMAScript specification is a standardized specification of a scripting language. There are six editions of ECMA-262 published. Version 6 of the standard is codenamed «Harmony». TypeScript is aligned with the ECMAScript6 specification.

TypeScript adopts its basic language features from the ECMAScript5 specification, i.e., the official specification for JavaScript. TypeScript language features like Modules and class-based orientation are in line with the EcmaScript 6 specification. Additionally, TypeScript also embraces features like generics and type annotations that aren’t a part of the EcmaScript6 specification.

4: Использование gts

Установив линтер, вы можете использовать сторонние инструменты, чтобы избежать необходимости настраивать линтинг и конфигурацию в файле tsconfig.json. Google TypeScript Style (сокращенно gts) – один из таких инструментов. Он представляет собой руководство по написанию кода, линтер и автоматический корректор кода – все в одном. Инструмент gts поможет вам быстро запустить новый проект TypeScript и избежать сбоев в его работе. Также gts предлагает довольно необычную конфигурацию по умолчанию, которую не придется долго настраивать.

Чтобы протестировать gts, давайте попробуем создать новую папку проекта. Когда папка проекта будет готова, инициализируйте gts с помощью следующей команды:

Приведенная выше команда сгенерирует все, что вам нужно для начала работы с TypeScript, включая файл tsconfig.json и настройку линтинга. Также она создаст файл package.json, если его еще нет.

Кроме того, команда npx gts init добавит в файл package.json полезные сценарии npm. Например, теперь для компиляции вашего проекта TypeScript вы можете запустить команду npm run compile. Чтобы проверить наличие ошибок с помощью линтера, вы можете запустить npm run check.

Примечание: Изучите документацию по gts, чтобы узнать, как интегрировать gts с линтером ESLint.

Чтобы использовать TSLint в проекте TypeScript, вам все равно необходимо установить TSLint и запустить npx tslint –init, чтобы создать конфигурационный файл tslint.json. В предыдущем разделе мы расширили TSLint, интегрировав руководство Airbnb. Для gts нужно сделать то же самое:

{
  "defaultSeverity": "error",
  "extends": [
    "./node_modules/gts/tslint.json"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

Теперь TSLint будет следовать правилам линтинга, установленным gts.

Итак, gts установлен и интегрирован в ваш проект TypeScript. Используя gts, вы сможете быстро создавать новые проекты TypeScript с необходимыми конфигурациями.

# Using TypeScript

As XState is written in TypeScript(opens new window), strongly typing your statecharts is useful and encouraged.

Providing the context and events to the attribute gives many advantages:

  • The context type/interface () is passed on to actions, guards, services and more. It is also passed to deeply nested states.
  • The event type () ensures that only specified events (and built-in XState-specific ones) are used in transition configs. The provided event object shapes are also passed on to actions, guards, and services.
  • Events which you send to the machine will be strongly typed, offering you much more confidence in the payload shapes you’ll be receiving.

Middleware

Middleware functions have access to the request and response objects.  It can attach to any place in the request-response cycle. A third argument that middleware receives is the next function. When called, the next middleware in the chain is executed. An example of a middleware is the get callback that handles the HTTP GET request that we’ve written above. It is a very specific middleware that executes on a particular case. They can also perform more generic tasks. Let’s create a very simple logger middleware that will log to console what requests were made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import*asexpress from’express’;

functionloggerMiddleware(requestexpress.Request,responseexpress.Response,next){

console.log(`${request.method}${request.path}`);

next();

}
 

constapp=express();

app.use(loggerMiddleware);

app.get(‘/hello’,(request,response)=>{

response.send(‘Hello world!’);

});

app.listen(5000);

In this example, as soon as someone sends the GET request to the /hello path, “GET /hello” will be printed in the console in which the app runs. In fact, it runs even when someone requests a page that you don’t have a handler for.

Thanks to calling next(), the control of the request can be passed further. If you create a middleware that neither ends the request-response cycle (for example by sending a response) or calls the next function, the request will not finish with a valid response.

There are a lot of ready to use middlewares that you can attach to your application and you will have plenty of chances to see some of them in this course. A crucial one is the body-parser. It parses the body of the incoming request and makes it available under the request.body property. In this example, we use the bodyParser.json middleware that parses the json data.

1 npm install body-parser
1
2
3
4
5
6
7
8
9
10
11
12

import*asexpress from’express’;

import*asbodyParser from’body-parser’;

constapp=express();

app.use(bodyParser.json());

app.post(‘/’,(request,response)=>{

response.send(request.body);

});

app.listen(5000);

The body was sent back to us thanks to running  response.send(request.body). Without the body parser, the request.body property wouldn’t be accessible.

As we go further, we explain more advanced concepts connected to the middleware.

Типы возвращаемых значений

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

function add(x: number, y: number): number {
    return x+y;
}

var myAdd = function(x: number, y: number): number { return x+y; };

Написание типа функции

Функция представляет из себя тип. Рассмотрим полное написание типа функции.

var myAdd: (x:number, y:number)=>number = 
    function(x: number, y: number): number { return x+y; };

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

var myAdd: (baseValue:number, increment:number)=>number = 
    function(x: number, y: number): number { return x+y; };

. Тип возвращаемого значения указывается после стрелки =>

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

Выведение типов

Компилятор TypeScript может сам определять тип выражения, основываясь на типах аргументов:

// myAdd имеет полное описание типа функции
var myAdd = function(x: number, y: number): number { return x+y; };

// Параметры 'x' и 'y' имеют тип number
var myAdd: (baseValue:number, increment:number)=>number = 
    function(x, y) { return x+y; };

Это называется ‘контекстная типизация’. Это позволяет сократить усилия, чтобы программа была типизированной.

Композиция

Идея состоит в том, чтобы создать что-то из других частей. Зачем нам это делать? Что ж, проще построить что-то сложное, если оно состоит из множества маленьких частей, которые мы понимаем. Другая причина — возможность повторного использования. Большие и более сложные вещи могут иногда разделяться на части, из которых они состоят, с другими большими и сложными вещами. Вы когда-нибудь слышали об ИКЕА?

В программировании есть несколько типов композиций! Далее мы рассмотрим что такое Наследование, Композиция функций и Композиция объекта (с классами и без классов)

Композиция против Наследования

Давайте быстро объясним что такое наследование. Идея наследования состоит в том, чтобы наследовать признаки, поля, а также методы от родительского класса. Класс, наследуемый от родительского класса, называется подклассом. Это наследование позволяет обрабатывать группу объектов одинаковым образом. Рассмотрим приведенный ниже пример:

class Shape {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Movable extends Shape {
  move(dx, dy) {
    this.x += dx;
    this.y += dy;
  }
}

class Hero extends Movable {
  constructor(x, y) {
    super(x, y);
    this.name = 'hero';
  }
}

class Monster extends Movable {
  constructor(x, y) {
    super(x, y);
    this.name = 'monster';
  }
}

const movables = ;
movables.forEach(m => m.move(2, 3));

В примере мы можем обрабатываем Hero и Monster одинаковым образом, поскольку они имеют общий элемент-предок Movable, который позволяет перемещать их с помощью метода move(). Все это основано на принципе отношений IS-A. Hero IS-A Movable, Monster IS-A Movable.

В последнее время в разные источниках много говорилось о том, что желательнее использовать композицию, а не наследование. Почему? Давайте посмотрим на некоторые недостатки наследования:

Принцип подстановки Лисков, идея этого принципа заключается в том, что код должен работать, даже если заменить что-то общим предком на что-то другое, то есть, заменить Hero на Monster, так как они оба имеют тип Movable. В приведенном выше примере кода эта замена должна работать. Тем не менее, приведенный выше код представляет собой идеальный случай. Реальность намного хуже. В действительности, могут существовать большие кодовые базы, где существует более 20 уровней наследования, и унаследованные методы могут быть не реализованы должным образом, что означает, что некоторые объекты нельзя просто так заменять друг на друга. Рассмотрим следующий код:

   class NPC extends Movable {
     move(dx, dy) {
       console.log('I wont move')
     }
   }

Вышеуказанный код нарушил принцип подстановки Лискова. К счастью наша кодовая база настолько мала, что мы можем легко обнаружить нарушение. В больших кодовых базах вы не сможете определить, когда это произойдет. Представьте, что нарушение происходит на третьем уровне наследования, а всего у вас есть 20 уровней наследования.

Отсутствие гибкости, в большинстве случаев у нас есть отношения HAS-A по сравнению с IS-A. Легче думать о том, что разные компоненты делают разные вещи, а не имеют ничего общего тогда нам будет легче создавать множество дополнительных классов и цепочек взаимодействий.

Композиция функций

Это математический термин, утверждающий согласно Википедии следующее: композиция функций — это операция, которая принимает две функции f и g и производит функцию h такую, что h (x) = g (f (x)).

В программировать мы можем создать такой пример:

   let list = ;
   take(orderByAscending(list), 3)

Где list это x, f(x) это orderByAscending(list) а g(x) это take() c f(x) входным параметром.

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

Шаг 3 — Настройка TypeScript

В этом разделе мы настроим TypeScript и проверку соблюдения стандартов для TypeScript. TypeScript использует файл для настройки опций компилятора для проекта. Создайте файл в корне каталога проекта и вставьте следующий фрагмент кода:

tsconfig.json

Давайте рассмотрим некоторые ключи во фрагменте кода JSON выше:

  • : указывает метод генерирования кода модуля. Node использует .
  • : указывает уровень языка на выходе.
  • : помогает компилятору определить, на что ссылается импорт. Значение имитирует механизм разрешения модуля Node.
  • : Это место для вывода файлов после транспиляции. В этом учебном модуле мы сохраним его как .

В качестве альтернативы созданию и заполнения файла вручную можно запустить следующую команду:

Эта команда сгенерирует файл с правильными комментариями.

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

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

Откройте сгенерированный файл и добавьте соответствующее правило :

tslint.json

По умолчанию модуль проверки TypeScript предотвращает использование отладки через команды , поэтому нужно явно предписать ему отключить правило по умолчанию .

Connect Your Feature Flag with Node

Back in the application code, Split Node.js SDK is needed to apply the previously set logic in the application runtime. It can be installed via npm, and it also ships with the TypeScript declaration files, so you don’t need to install a separate package for that:

Add the following code in the . Optionally, you can put the statement at the top of the file.

The API key you’ll use here is the one you can see in the Admin Settings of the Split dashboard. The key you search for is the second one from the – staging one for the SDK. Of course, in a production app, it is considered a good practice to store this key as an environment variable on your machine.

As SDK now communicates with the app, it can be utilized to get a respective treatment for a user’s request with the method. The method receives two arguments – key and split name. The key is often something used to identify a particular user and calculate a specific treatment for that user. Simultaneously, the split name is the identifier of the split configured in the Split dashboard.

A good idea is to put the logic for calculating the user’s treatment inside an Express middleware – a function that will be executed against each API request before proceeding further. That middleware can read the user’s authentication data, e.g., the data stored in the header, and use it as a key for the method. The second argument is the name of the previously configured split ().

Place the following code above the line:

The sole purpose of the is to put the treatment on the object and proceed to the next middleware, which is the function.

After adding this code, you’ll be getting an error from the TypeScript compiler – and a completely legit one – as there is no property present on the interface, which is a type assigned to the parameter. You shouldn’t think of this as a bad thing – TypeScript is doing here what the language was made for – warning the developer about the type errors in compile time to avoid (much more severe) errors for the end-user in the runtime. The compile error can be avoided by using a technique called declaration merging. That will effectively extend the interface provided by Express with your custom property.

The way to expand Express declaration types is to create a declaration file inside the custom folder, with a structure that simulates the one located in That means creating an file located at that will expand on Express type definitions found at .

Create the file with:

Your project tree should look similar to the structure on the image:

Populate the file with this code:

Were you wondering about this wandering statement from above? It is needed for this file to be understood as a typescript module, as only files with top-level or statements are interpreted as modules.

Add the property to the file, so the file now looks like this:

This will ensure that the TypeScript compiler will search for types not only inside the folder, which is the default but also in the custom folder that you’ve made. Finally, you can use the property inside the interface in the , and the error in the console should disappear.

Let’s take a quick look on the angle bracket syntax () in this line of the middleware: . The angle brackets provide a nice TypeScript feature of type casting a variable from one type to another. In this particular case, , of type , is casted into type, as function’s type definition expects the first argument to be of the type.

Edit the routing line by adding a treatment middleware:

Now it’s time to use the value for branching inside the endpoint function.

How React and TypeScript Work Together

Before we begin, let’s revisit how React and TypeScript work together. React is a “JavaScript library for building user interfaces”, while TypeScript is a “typed superset of JavaScript that compiles to plain JavaScript.” By using them together, we essentially build our UIs using a typed version of JavaScript.

The reason you might use them together would be to get the benefits of a statically typed language (TypeScript) for your UI. This means more safety and fewer bugs shipping to the front end.

Does TypeScript Compile My React Code?

A common question that’s always good to review is whether TypeScript compiles your React code. The way TypeScript works is similar to this interaction:

TS: “Hey, is this all your UI code?”React: “Yup!”TS: “Cool! I’m going to compile it and make sure you didn’t miss anything.”React: “Sounds good to me!”

So the answer is yes, it does! But later, when we cover the settings, most of the time you’ll want to use . What this means is TypeScript will not emit JavaScript out after compilation. This is because typically, we’re just utilizing TypeScript to do our type-checking.

The output is handled, in a CRA setting, by . We run and bundles the output for production.

To recap, TypeScript compiles your React code to type-check your code. It doesn’t emit any JavaScript output (in most scenarios). The output is still similar to a non-TypeScript React project.

Can TypeScript Work with React and webpack?

Yes, TypeScript can work with React and webpack. Lucky for you, the webpack documentation has a guide on that.

Hopefully, that gives you a gentle refresher on how the two work together. Now, on to best practices!

Controllers

A common way of structuring an Express application is called Model-View-Controller. Some of the key components of MVC are controllers. They contain the logic of the application and deal with handling client requests. Since this course covers TypeScript Express, we use classes. For the sake of readable code, I also create a class for the app instance itself.

src/server.ts
1
2
3
4
5
6
7
8
9
10
11

import App from’./app’;

import PostsController from’./posts/posts.controller’;

constapp=newApp(

newPostsController(),

,

5000,

);

app.listen();

src/app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

import*asexpress from’express’;

import*asbodyParser from’body-parser’;

classApp{

public app:express.Application;

public port:number;

constructor(controllers,port){

this.app=express();

this.port=port;

this.initializeMiddlewares();

this.initializeControllers(controllers);

}

privateinitializeMiddlewares(){

this.app.use(bodyParser.json());

}

privateinitializeControllers(controllers){

controllers.forEach((controller)=>{

this.app.use(‘/’,controller.router);

});

}

publiclisten(){

this.app.listen(this.port,()=>{

console.log(`Applisteningontheport${this.port}`);

});

}

}
 

export defaultApp;

src/posts/post.interface.ts
1
2
3
4
5
6
7

interfacePost{

authorstring;

contentstring;

titlestring;

}
 

export defaultPost;

src/posts/posts.controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

import*asexpress from’express’;

import Post from’./post.interface’;

classPostsController{

publicpath=’/posts’;

publicrouter=express.Router();

private posts:Post=

{

author’Marcin’,

content’Dolor sit amet’,

title’Lorem Ipsum’,

}

;

constructor(){

this.intializeRoutes();

}

publicintializeRoutes(){

this.router.get(this.path,this.getAllPosts);

this.router.post(this.path,this.createAPost);

}

getAllPosts=(requestexpress.Request,responseexpress.Response)=>{

response.send(this.posts);

}

createAPost=(requestexpress.Request,responseexpress.Response)=>{

const post:Post=request.body;

this.posts.push(post);

response.send(post);

}

}
 

export defaultPostsController;

The code above results in creating the route named /posts that responds on the GET and POST request, storing and displaying the list of posts. In the upcoming parts of the Typescript Express course, we continue to use controllers to structure our code.

The getAllPosts and createAPost are arrow functions because they access properties of an instance of the class. Since they are passed to the router and not called directly, the context changes. You can achieve the same result by calling  this.router.get(this.path,this.getAllPosts.bind(this))

Минусы TypeScript​

Разработчики любят этот язык, а некоторые крупные проекты уже переходят на него. Например, популярный фреймворк Angular.JS. Но этого всё равно недостаточно, чтобы он стал таким же востребованным, как JavaScript. Это связано с тем, что разработка веб-приложения на TypeScript стоит дороже и отнимает больше времени.

Особенно если необходимо использовать какую-нибудь библиотеку или фреймворк, которые не портированы на TS. В этом случае разработчикам придётся самостоятельно описывать сигнатуры (указывать типы данных) всех функций и методов — достаточно длительный процесс, учитывая размеры современных библиотек.

Также порог входа в TypeScript выше — чтобы использовать его преимущества, важно знать типы данных и объектно-ориентированное программирование

Why should you use Typescript?

There are many important benefits to using Typescript. Let’s break them down.

Typescript catches mistakes in your JavaScript code earlier on. Typescript has the ability to catch bugs and errors before runtime, so you’ll write reliable code and mitigates the pitfalls of JavaScript that are only found at runtime.

  • Transpiling allows you to generate ECMAScript, and you can specify which version of JavaScript you prefer to use. This means that you can write code that is compatible with old browsers, all while using the newest tools.

  • Typescript supports JS libraries and API documentation, including JQuery, BootStrapJS, React, and more. You can use all the familiar tools you already know, so the learning curve isn’t too bad.

  • Typescript introduces static typing to structure your code and improve object-oriented programming techniques. The static typing feature of Typescript also makes the code easier to refactor, since you can navigate to references of functions members.

  • Typescript uses NPM, which gives you access to millions of reliable libraries. This also makes it far easier to learn Typescript, as you don’t have to make custom tools to access libraries.

  • Typescript is easier to maintain. The language is generally easier to read and access. The built-in self-documentation makes it easier to check on types and objects in your code.

  • Typescript makes it easier to use React, Angular, and Vue. Typescript integrates well with these frameworks, particularly React, which has been described as a perfect fit with Typescript. The usage of Typescript is not mandatory for these frameworks, but it can add productivity and ease.

String

Для хранения строк TypeScript использует двойные
» или одинарные
‘  для обрамления строк.

let color: string = «blue»;
color = ‘red’;

1
2

let color: string = «blue»;
color = ‘red’;

Вы также можете использовать шаблоны строк, которые могут занимать несколько строк и содержать вычисляемые выражения внутри себя. Эти строки окружаются обратной кавычкой
`  (которая на клавиатуре обычно расположена на клавише с буквой «ё»). Вычисляемые выражения внутри шаблонов строк пишутся в виде
${выражение}.

let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.

I’ll be ${ age + 1 } years old next month.`;

1
2
3
4
5

let fullNamestring=`Bob Bobbington`;

let agenumber=37;

let sentencestring=`Hello,mynameis${fullName}.

I’llbe${age+1}years old next month.`;

Вышеприведённый код запишет в переменную
sentence то же значение, что и вот такой:

let sentence: string = «Hello, my name is » + fullName + «.\n\n» +
«I’ll be » + (age + 1) + » years old next month.»;

1
2

let sentencestring=»Hello, my name is «+fullName+».\n\n»+

«I’ll be «+(age+1)+» years old next month.»;

Обратная совместимость

После компиляции кода на TypeScript создаётся обычный код JavaScript, который можно сразу использовать в проекте. Переписать проект на TS можно буквально по частям: потихоньку перерабатывать модули один за другим, когда на это будут ресурсы. Никаких конфликтов не возникнет.

Эту статью мы написали по мотивам интервью с Александром Штыковым — фронтенд-лидом Деловой Среды. С недавних пор TypeScript стал стандартом во всех проектах, над которыми работают команды Александра.

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

Эксперт

Александр Штыков

Текст и иллюстрации

Слава Уфимцев

Редактор

Максим Ильяхов

Корректор

Ирина Михеева

Художник

Даня Берковский

Вёрстка

Мария Дронова

Соцсети

Олег Вешкурцев

Во имя

строгих типов данных

Что такое TypeScript

TypeScript — это язык программирования, в котором исправлены многие недостатки JavaScript. Код на TypeScript выглядит почти так же, как и код на JS, и, если у вас есть опыт frontend-разработки, изучить TypeScript достаточно просто. Особенно учитывая, что вы можете писать JS-код прямо в TS-скриптах.

Код на TypeScript компилируется в JS и подходит для разработки любых проектов под любые браузеры — тем более что можно выбрать версию JS, в которую будет компилироваться код.

TypeScript — проект с открытым исходным кодом, поэтому он очень быстро развивается. Многое, что появляется в TS, позже переходит и в JavaScript: например, let и const, стрелочные функции и так далее.

Давайте разберём два главных преимущества TS перед JS.

Строгая типизация

Многие проблемы в JavaScript появляются из-за динамической типизации и в целом странного поведения типов данных:

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

Улучшенное ООП

И в JS, и в TS есть поддержка объектно-ориентированного программирования: классы, объекты, наследование. Однако TypeScript шагнул чуть дальше и использует больше возможностей ОПП. В том числе, например, интерфейсы:

Другой большой плюс — модификаторы доступа. Их в TypeScript три: public, private и protected. Вот пример их использования:

Также есть и другие возможности:

  • определение полей в конструкторе;
  • преобразование типов;
  • абстрактные классы;
  • обобщение и так далее.
Гость форума
От: admin

Эта тема закрыта для публикации ответов.