SlideShare a Scribd company logo
TypeScript 2 in action
Александр Русаков / Techops
a_s_rusakov@mail.ru
github.com/arusakov
Немного истории
TypeScript 1.8 22 февраля 2016 г.
TypeScript 2.0 22 сентября 2016 г.
TypeScript 2.1 7 декабря 2016 г.
TypeScript 2.2 RC 2 февраля 2017 г.
blogs.msdn.microsoft.com/typescript/ 2
О чем пойдет речь
● Защита от Undefined / Null
● Literal Types и что это такое
● Размеченные объединения и Redux
● Типизация для React Component API
3
Undefined everywhere
4
Undefined / Null
TypeError: Cannot read property 'x' of undefined
TypeError: Cannot read property 'y' of null
5
Undefined / Null
type User = {
name: string
tags?: string[]
}
function getTags(user: User) {
return user.tags.join(', ')
}
6
type User = {
name: string
tags?: string[]
}
function getTags(user: User) {
return user.tags.join(', ')
}
Undefined / Null
7
type User = {
name: string
tags?: string[]
}
function getTags(user: User) {
return user.tags.join(', ')
}
Undefined / Null
8
Non-Nullable Types
https://github.com/Microsoft/TypeScript/pull/7140
// tsc --strictNullChecks
function getTags(user: User) {
return user.tags.join(', ')
}
// ERROR: Object is possibly 'undefined'
9
Non-Nullable Types
// tsc --strictNullChecks
function getTagStrict(user: User) {
return user.tags && user.tags.join(', ')
}
10
Non-Null Assertion !
// tsc --strictNullChecks
function getTagForce(user: User) {
return user.tags!.join(', ')
}
11
Literal Types
12
???
font-weight
13
Какие допустимые значения этого CSS свойства?
font-weight
14
Какие допустимые значения этого CSS свойства?
initial, inherit, unset,
normal, bold, bolder, lighter
100, 200, 300, 400, 500, 600, 700, 800, 900
https://www.w3.org/TR/css-fonts-3/#font-weight-prop
font-weight
15
type fontWeight = number | string
<div style={{ fontWeight: 1000 }} />
<div style={{ fontWeight: 'ligther' }} />
font-weight
16
type fontWeight = number | string
<div style={{ fontWeight: 1000 }} />
<div style={{ fontWeight: 'ligther' }} />
font-weight
17
type fontWeight = number | string
<div style={{ fontWeight: 1000 }} />
<div style={{ fontWeight: 'ligther' }} />
Literal Types
18
type fontWeight =
'initial' | 'inherit' | 'unset' |
'normal' | 'bold' | 'bolder' | 'lighter' |
100 | 200 | 300 | 400 | 500 |
600 | 700 | 800 | 900
https://github.com/Microsoft/TypeScript/pull/9407
Literal Types
19
<div style={{ fontWeight: 1000 }} />
<div style={{ fontWeight: 'ligther' }} />
// ERROR: Types of property 'fontWeight' are incompatible.
TypeScript 1 + Redux
import { Action } from 'redux' // Interface
const ACTION_TYPE_1 = 'type1'
interface Action1 extends Action {
data: number
}
20
TypeScript 1 + Redux
function reduce(state, action: Action) {
switch (action.type) {
case ACTION_TYPE_1:
action.data
}
}
21
TypeScript 1 + Redux
function reduce(state, action: Action) {
switch (action.type) {
case ACTION_TYPE_1:
action.data
}
}
// ERROR: Property 'data' does not exist on type 'Action'
22
TypeScript 1 + Redux
23
function reduce(state, action: Action) {
switch (action.type) {
case ACTION_TYPE_1:
(action as Action1).data // number
}
}
TypeScript 1 + Redux ≠ ♥
24
TypeScript 2
25
Discriminated Union Types
type Action =
{ type: 'type1', id: number } |
{ type: 'type2', name: string }
26https://github.com/Microsoft/TypeScript/pull/9163
Discriminated Union Types
const ACTION_TYPE1 = 'type1'
const ACTION_TYPE2 = 'type2'
27
Discriminated Union Types
const ACTION_TYPE1 = 'type1'
const ACTION_TYPE2 = 'type2'
type Action =
{ type: typeof ACTION_TYPE1, id: number } |
{ type: typeof ACTION_TYPE2, name: string }
28
TypeScript 2 ♥ Redux
https://spin.atomicobject.com/2016/09/27/typed-redux-reducers-typescript-2-0/
switch (action.type) {
case ACTION_TYPE1:
action.id // number
case ACTION_TYPE2:
action.name // string
}
29
React
30
TypeScript 1 + React
type State = { x: number, y: string }
this.state.x = 1
this.setState({ y: e.target.value })
31
TypeScript 1 + React
type State = { x: number, y: string }
this.state.x = 1
this.setState({ y: e.target.value })
// ERROR: Property 'x' is missing
32
TypeScript 1 + React
type State = { x: number, y: string }
this.state.x = 1
this.setState({ y: e.target.value } as State)
33
TypeScript 1 + React ≠ ♥
34
Index+Mapped Types
// react.d.ts
class Component<P, S> {
setState<K extends keyof S>(s: Pick<S, K>): void;
props: Readonly<P>;
state: Readonly<S>;
}
35
https://github.com/Microsoft/TypeScript/pull/11929
https://github.com/Microsoft/TypeScript/pull/12114
TypeScript 2 ♥ React
type State = { x: number, y: string }
this.state.x = 1
// ERROR: Cannot assign because it is a read-only property
this.setState({ y: e.target.value })
36
Predefined Mapped Types
// lib.es6.d.ts
Pick<T, K extends keyof T>
Readonly<T>
Partial<T>
Record<K extends string, T>
37
В заключение
38
github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript
github.com/Microsoft/TypeScript/wiki/Roadmap
Спасибо за внимание
Вопросы?
Презентация и материалы: bit.ly/2kzGfOP
Александр Русаков / Techops
a_s_rusakov@mail.ru
github.com/arusakov

More Related Content

What's hot (20)

PPTX
002. Introducere in type script
Dmitrii Stoian
 
PPTX
TypeScript - Silver Bullet for the Full-stack Developers
Rutenis Turcinas
 
PDF
Typescript for the programmers who like javascript
Andrei Sebastian Cîmpean
 
PDF
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
PPTX
Type script - advanced usage and practices
Iwan van der Kleijn
 
PPTX
TypeScript Overview
Aniruddha Chakrabarti
 
ODP
Getting started with typescript and angular 2
Knoldus Inc.
 
PDF
TypeScript - An Introduction
NexThoughts Technologies
 
PPTX
Typescript 101 introduction
Bob German
 
PDF
TypeScript introduction to scalable javascript application
Andrea Paciolla
 
PPTX
Typescript Fundamentals
Sunny Sharma
 
PDF
Power Leveling your TypeScript
Offirmo
 
PPT
TypeScript Presentation
Patrick John Pacaña
 
PPTX
Typescript ppt
akhilsreyas
 
PPTX
TypeScript 101
rachelterman
 
PPTX
Typescript in 30mins
Udaya Kumar
 
DOC
Typescript Basics
Manikandan [M M K]
 
PPTX
Typescript
Nikhil Thomas
 
PPTX
JS Event Loop
Saai Vignesh P
 
PPTX
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 
002. Introducere in type script
Dmitrii Stoian
 
TypeScript - Silver Bullet for the Full-stack Developers
Rutenis Turcinas
 
Typescript for the programmers who like javascript
Andrei Sebastian Cîmpean
 
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
Type script - advanced usage and practices
Iwan van der Kleijn
 
TypeScript Overview
Aniruddha Chakrabarti
 
Getting started with typescript and angular 2
Knoldus Inc.
 
TypeScript - An Introduction
NexThoughts Technologies
 
Typescript 101 introduction
Bob German
 
TypeScript introduction to scalable javascript application
Andrea Paciolla
 
Typescript Fundamentals
Sunny Sharma
 
Power Leveling your TypeScript
Offirmo
 
TypeScript Presentation
Patrick John Pacaña
 
Typescript ppt
akhilsreyas
 
TypeScript 101
rachelterman
 
Typescript in 30mins
Udaya Kumar
 
Typescript Basics
Manikandan [M M K]
 
Typescript
Nikhil Thomas
 
JS Event Loop
Saai Vignesh P
 
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 

Viewers also liked (12)

PDF
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
Micael Gallego
 
PPTX
TypeScript
GetDev.NET
 
PPTX
Typescript tips & tricks
Ori Calvo
 
PDF
Angular 2 - Typescript
Nathan Krasney
 
PDF
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
Ontico
 
PDF
TypeScript Seminar
Haim Michael
 
PDF
Typescript + Graphql = <3
felixbillon
 
PPTX
TypeScript
Udaiappa Ramachandran
 
PDF
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
MoscowJS
 
PPTX
Why TypeScript?
FITC
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PDF
TypeScriptで快適javascript
AfiruPain NaokiSoga
 
TypeScript: Un lenguaje aburrido para programadores torpes y tristes
Micael Gallego
 
TypeScript
GetDev.NET
 
Typescript tips & tricks
Ori Calvo
 
Angular 2 - Typescript
Nathan Krasney
 
TypeScript: особенности разработки / Александр Майоров (Tutu.ru)
Ontico
 
TypeScript Seminar
Haim Michael
 
Typescript + Graphql = <3
felixbillon
 
«Typescript: кому нужна строгая типизация?», Григорий Петров, MoscowJS 21
MoscowJS
 
Why TypeScript?
FITC
 
TypeScript Introduction
Dmitry Sheiko
 
TypeScriptで快適javascript
AfiruPain NaokiSoga
 
Ad

Similar to Александр Русаков - TypeScript 2 in action (20)

PDF
Practical TypeScript
ldaws
 
PPTX
Type script is awesome
KeithMurgic
 
PPTX
Introduction to TypeScript
KeithMurgic
 
PPTX
"Enhancing Your React with Advanced TypeScript", Titian Cernicova-Dragomir
Fwdays
 
PDF
Flow or Type - how to React to that?
Krešimir Antolić
 
PDF
Introduction to typescript
Mario Alexandro Santini
 
PPT
TypeScript.ppt LPU Notes Lecture PPT for 2024
manveersingh2k05
 
PDF
Milano JS Meetup - Gabriele Petronella - Codemotion Milan 2016
Codemotion
 
PDF
Type Script Conceitos de ts para projetos front-end React - por ruben marcus
Ruben Marcus Luz Paschoarelli
 
PDF
JavaScript, TypeScipt and React Native
Mitchell Tilbrook
 
PPTX
Type Driven Development with TypeScript
Garth Gilmour
 
PDF
Typescript presentation
Kartik Grewal
 
PDF
Typescript - interesting parts
Mykyta Khmel
 
PPTX
Type script
Zunair Shoes
 
PDF
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
Typescript: Beginner to Advanced
Talentica Software
 
PDF
An Introduction to TypeScript
WrapPixel
 
PPTX
SubmitJS: Is react + redux + typescript a good combination? Dmytro Beseda
Binary Studio
 
PDF
Introduction to Type Script by Sam Goldman, SmartLogic
SmartLogic
 
PDF
TypeScript Introduction
Hans Höchtl
 
Practical TypeScript
ldaws
 
Type script is awesome
KeithMurgic
 
Introduction to TypeScript
KeithMurgic
 
"Enhancing Your React with Advanced TypeScript", Titian Cernicova-Dragomir
Fwdays
 
Flow or Type - how to React to that?
Krešimir Antolić
 
Introduction to typescript
Mario Alexandro Santini
 
TypeScript.ppt LPU Notes Lecture PPT for 2024
manveersingh2k05
 
Milano JS Meetup - Gabriele Petronella - Codemotion Milan 2016
Codemotion
 
Type Script Conceitos de ts para projetos front-end React - por ruben marcus
Ruben Marcus Luz Paschoarelli
 
JavaScript, TypeScipt and React Native
Mitchell Tilbrook
 
Type Driven Development with TypeScript
Garth Gilmour
 
Typescript presentation
Kartik Grewal
 
Typescript - interesting parts
Mykyta Khmel
 
Type script
Zunair Shoes
 
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
Typescript: Beginner to Advanced
Talentica Software
 
An Introduction to TypeScript
WrapPixel
 
SubmitJS: Is react + redux + typescript a good combination? Dmytro Beseda
Binary Studio
 
Introduction to Type Script by Sam Goldman, SmartLogic
SmartLogic
 
TypeScript Introduction
Hans Höchtl
 
Ad

More from MoscowJS (20)

PDF
Виктор Розаев - Как не сломать обратную совместимость в Public API
MoscowJS
 
PDF
Favicon на стероидах
MoscowJS
 
PDF
E2E-тестирование мобильных приложений
MoscowJS
 
PDF
Reliable DOM testing with browser-monkey
MoscowJS
 
PDF
Basis.js - Production Ready SPA Framework
MoscowJS
 
PDF
Контекст в React, Николай Надоричев, MoscowJS 31
MoscowJS
 
PDF
Верстка Canvas, Алексей Охрименко, MoscowJS 31
MoscowJS
 
PDF
Веб без интернет соединения, Михаил Дунаев, MoscowJS 31
MoscowJS
 
PDF
Angular2 Change Detection, Тимофей Яценко, MoscowJS 31
MoscowJS
 
PDF
Создание WYSIWIG-редакторов для веба, Егор Яковишен, Setka, MoscowJs 33
MoscowJS
 
PDF
Предсказуемый Viewport, Вопиловский Константин, KamaGames Studio, MoscowJs 33
MoscowJS
 
PDF
Promise me an Image... Антон Корзунов, Яндекс, MoscowJs 33
MoscowJS
 
PDF
Регрессионное тестирование на lenta.ru, Кондратенко Павел, Rambler&Co, Moscow...
MoscowJS
 
PDF
"Опыт разработки универсальной библиотеки визуальных компонентов в HeadHunter...
MoscowJS
 
PDF
"Во все тяжкие с responsive images", Павел Померанцев, MoscowJS 29
MoscowJS
 
PDF
"AMP - технология на три буквы", Макс Фролов, MoscowJS 29
MoscowJS
 
PDF
"Observable и Computed на пример KnockoutJS", Ольга Кобец, MoscowJS 29
MoscowJS
 
PDF
«Пиринговый веб на JavaScript», Денис Глазков, MoscowJS 28
MoscowJS
 
PDF
"Доклад не про React", Антон Виноградов, MoscowJS 27
MoscowJS
 
PDF
"Web Audio Api", Анатолий Найда, MoscowJS 27
MoscowJS
 
Виктор Розаев - Как не сломать обратную совместимость в Public API
MoscowJS
 
Favicon на стероидах
MoscowJS
 
E2E-тестирование мобильных приложений
MoscowJS
 
Reliable DOM testing with browser-monkey
MoscowJS
 
Basis.js - Production Ready SPA Framework
MoscowJS
 
Контекст в React, Николай Надоричев, MoscowJS 31
MoscowJS
 
Верстка Canvas, Алексей Охрименко, MoscowJS 31
MoscowJS
 
Веб без интернет соединения, Михаил Дунаев, MoscowJS 31
MoscowJS
 
Angular2 Change Detection, Тимофей Яценко, MoscowJS 31
MoscowJS
 
Создание WYSIWIG-редакторов для веба, Егор Яковишен, Setka, MoscowJs 33
MoscowJS
 
Предсказуемый Viewport, Вопиловский Константин, KamaGames Studio, MoscowJs 33
MoscowJS
 
Promise me an Image... Антон Корзунов, Яндекс, MoscowJs 33
MoscowJS
 
Регрессионное тестирование на lenta.ru, Кондратенко Павел, Rambler&Co, Moscow...
MoscowJS
 
"Опыт разработки универсальной библиотеки визуальных компонентов в HeadHunter...
MoscowJS
 
"Во все тяжкие с responsive images", Павел Померанцев, MoscowJS 29
MoscowJS
 
"AMP - технология на три буквы", Макс Фролов, MoscowJS 29
MoscowJS
 
"Observable и Computed на пример KnockoutJS", Ольга Кобец, MoscowJS 29
MoscowJS
 
«Пиринговый веб на JavaScript», Денис Глазков, MoscowJS 28
MoscowJS
 
"Доклад не про React", Антон Виноградов, MoscowJS 27
MoscowJS
 
"Web Audio Api", Анатолий Найда, MoscowJS 27
MoscowJS
 

Recently uploaded (20)

PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Digital Circuits, important subject in CS
contactparinay1
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 

Александр Русаков - TypeScript 2 in action