Использовании TypeScript для Node.js
приложений
Nikita Galkin
1 / 25
Никита
Галкин
Backend разработчик
Люблю Highload, Opensource и Хакатоны
Умею делить монолиты на микросервисы
на PHP и Node.js
в компания Ciklum (ThomasCook)
galk-in galkin galk_in nikitagalkin
2 / 25
Внедрение инструмента возможно
только внутри процесса,
который его использует.
3 / 25
Процессы при разработке на JS
- Написания кода
- Документирование кода
- Транспайлинг
- Линтинг
- Написание и запуск тестов
4 / 25
Процессы при разработке на JS
- Написание и совместное использование спецификации
- Написание определений для библиотек
- Фиксирование версий библиотек
- Запуск Node.js
- Переход на TypeScript?
5 / 25
Написание кода
6 / 25
Книги:
Getting Started With TypeScript by Basarat
ng-book 2
Документация:
Официальная документация
Roadmap
Онлайн инструменты:
Песочница
Codepen
7 / 25
Документирование кода
8 / 25
/**
* Represents a book.
* @constructor
* @param {string} title - The title of the book.
* @param {string} author - The author of the book.
*/
function Book(title, author) {
...
}
type GenderType = "boy" | "girl";
interface User {
id: number;
name: string;
gender?: GenderType;
}
function buildUser(userId: number, userName: string): User {
return { id: userId, name: userName };
}
class UserFactory {
static createUser(id: number): User;
static createUser(id: number, name: string): User;
static createUser(id, name?): User {
if(name) {
return {id: id, name: name};
} else {
return UserFactory:findUser(id);
}
}
...
}
9 / 25
Транспайлинг
10 / 25
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false
},
"exclude": [
"node_modules"
]
}
package.json
...
"scripts": {
"build": "tsc",
"cs": "tslint --project tsconfig.json -t stylish",
"coveralls": "tsc --sourceMap && NODE_ENV=test istanbul cover ./node_modules/mocha/bin/_mocha && cat ./coverage/lcov.info | ./node_modules/cover
"test": "npm run cs && npm run build && npm run test:unit && npm run test:functional && npm run test:integration"
"test:functional": "NODE_ENV=test mocha ./test/functional/",
"test:integration": "NODE_ENV=test mocha ./test/integration/",
"test:unit": "NODE_ENV=test mocha ./test/unit/"
},
...
11 / 25
Линтинг
12 / 25
{
"rules": {
"member-access": false,
"no-any": false,
"no-var-requires": false,
"typedef": [
true,
"call-signature",
"arrow-call-signature",
"parameter"
],
"adjacent-overload-signatures": true,
"member-ordering": [
true,
{
"order": "fields-first"
}
],
"only-arrow-functions": false,
"no-internal-module": true,
"class-name": true,
"comment-format": [
true
],
"indent": [
true,
"spaces"
],
"no-console": [
true,
"debug",
"error",
"info",
"log",
"time",
13 / 25
Написание и запуск тестов
14 / 25
Транспайлинг тестов
или
Использовани компайлера
mocha test.ts --compilers
ts:typescript-require
15 / 25
Написание и совместное
использование спецификации
16 / 25
Input:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"hairColor": {
"enum": ["black", "brown", "blue"],
"type": "string"
}
},
"required": ["firstName", "lastName"]
}
17 / 25
Output:
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
}
18 / 25
Написание определений для библиотек
d.ts
19 / 25
{
"name": "msb",
"version": "0.11.6",
"description": "A framework to simplify the implementation of an event-bus oriented microservices architecture",
"license": "MIT",
"main": "index.js",
"typings": "msb.d.ts",
...
20 / 25
Фиксирование версий библиотек
Использовать shrinkwrap
Yarn не корректно работает с scoped packages @types
21 / 25
Запуск Node.js
22 / 25
ts-node
Execute TypeScript files with node
Interactive REPL
Execute (and print) TypeScript through the CLI
Uses source maps
Loads compiler options and .d.ts files from tsconfig.json
23 / 25
Переход на TypeScript
Пошаговое руководство
24 / 25
Вопросы?
Twitter galk.in
Email nikita@galk.in
Face2face at BeerJS
25 / 25

Использовании TypeScript для Node.js