SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Старовойт Андрей
Зачем нужен тип “true”?
PROFESSIONAL JS CONFERENCE
8-9 NOVEMBER‘19 KYIV, UKRAINE
@JetBrains. All rights reserved
About
—
• Работаю в команде WebStorm 5 лет
• Занимаюсь поддержкой JavaScript, TypeScript, JSX, …
@JetBrains. All rights reserved
Type “true”
—
@JetBrains. All rights reserved
Type “true”
—
let a: true;
TypeScript 2.0
@JetBrains. All rights reserved
Type “true”
—
let a: true;
a = true; //ok
a = false; //error
a = 1; //error
TypeScript 2.0
@JetBrains. All rights reserved
Зачем?
Type “true”
—
@JetBrains. All rights reserved
String Literal
Overloads
—
function create(p: “string"):string;
function create(p: "number"):number;
function create(p):any;
TypeScript 1.1
@JetBrains. All rights reserved
function create(p: true): string;
function create(p: false): number;
function create(p: boolean): string | number;
Type “true”
—
Boolean literals in overloads
@JetBrains. All rights reserved
_
@types/node TSLSocket
@JetBrains. All rights reserved
function check(checkType?: true);Optional
—
@JetBrains. All rights reserved
function check(checkType?: true);
check();
Optional
—
@JetBrains. All rights reserved
function check(checkType?: true);
check();
check(true);
Optional
—
@JetBrains. All rights reserved
_
@types/babel__core
@JetBrains. All rights reserved
TypeScript 2.0
Features
—
@JetBrains. All rights reserved
TypeScript 2.0
Features
—
@JetBrains. All rights reserved
Type Guard
—
@JetBrains. All rights reserved
class Cat { meow() }
class Dog { woof() }
function say(animal: Cat | Dog) {
if (animal instanceof Cat) {
animal.meow();
animal.woof();
}
}
Type Guard
—
@JetBrains. All rights reserved
class Cat { meow() }
class Dog { woof() }
function say(animal: Cat | Dog) {
if (animal instanceof Cat) {
animal.meow(); //ok, no cast
animal.woof(); //error
}
}
Type Guard
—
@JetBrains. All rights reserved
interface ICat { meow() }
interface IDog { woof() }
function say(animal: ICat | IDog) {
if (animal instanceof ICat) {
animal.meow();
}
}
Type Guard
—
@JetBrains. All rights reserved
interface ICat { meow() }
interface IDog { woof() }
function say(animal: ICat | IDog) {
if (animal instanceof ICat) {
animal.meow();
}
}
Type Guard
—
@JetBrains. All rights reserved
interface ICat { meow() }
interface IDog { woof() }
function say(animal: ICat | IDog) {
if (animal instanceof ICat) {
animal.meow();
}
}
//Compiled file
function say(animal) {
if (animal instanceof ICat) {
animal.meow();
}
}
Type Guard
—
@JetBrains. All rights reserved
Type Guard
—
Discriminated union types
@JetBrains. All rights reserved
interface ICat { kind: "cat"; meow() }
interface IDog { kind: "dog"; woof() }
function say(animal: ICat | IDog) {
if (animal.kind == "cat") {
animal.meow(); //ok
}
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
interface ICat { kind: "cat"; meow() }
interface IDog { kind: "dog"; woof() }
function say(animal: ICat | IDog) {
if (animal.kind == "cat") {
animal.meow(); //ok
}
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
interface ICat { kind: "cat"; meow() }
interface IDog { kind: "dog"; woof() }
function say(animal: ICat | IDog) {
if (animal.kind == "cat") {
animal.meow(); //ok
}
}
say({ kind: "cat" }) //error
Discriminated
Union Types
—
@JetBrains. All rights reserved
interface ICat { kind: "cat"; meow() }
interface IDog { kind: "dog"; woof() }
function say(animal: ICat | IDog) {
if (animal.kind == "cat") {
animal.meow(); //ok
}
}
say({ kind: "cat" }) //error
say({ kind: "cat", meow() {}}) //ok
Discriminated
Union Types
—
@JetBrains. All rights reserved
Boolean literals?
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result = {
success: boolean;
callback?() //if success=true
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result = {
success: boolean;
callback?() //if success=true
}
function process(p: Result) {
p.callback(); //ok, can throw error
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
p.callback(); //error
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
if (p.success) {
p.callback(); //ok
}
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
if (p.success) {
p.callback(); //ok
}
}
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
if (p.success) {
p.callback(); //ok
}
}
process({success : true}) //error
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
if (p.success) {
p.callback(); //ok
}
}
process({success : true}) //error
process({success : true, callback() {}}) //ok
Discriminated
Union Types
—
@JetBrains. All rights reserved
type Result =
{ success: true, callback() } |
{ success: false };
function process(p: Result) {
if (p.success) {
p.callback(); //ok
}
}
process({success : true}) //error
process({success : true, callback() {}}) //ok
Discriminated
Union Types
—
@JetBrains. All rights reserved
_
@types/jsforce
@JetBrains. All rights reserved
Literal Types
—
@JetBrains. All rights reserved
Literal Types
—
: true
: false
@JetBrains. All rights reserved
Literal Types
—
: true
: false
: boolean
@JetBrains. All rights reserved
Literal Types
—
: true
: false
: boolean
@JetBrains. All rights reserved
Const
—
const checkValue = true;
@JetBrains. All rights reserved
Const
—
const checkValue = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
@JetBrains. All rights reserved
Let
—
let checkValue: true = true;
@JetBrains. All rights reserved
Let
—
let checkValue: true = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
@JetBrains. All rights reserved
Let
—
let checkValue: true = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
checkValue = false; //error
@JetBrains. All rights reserved
Let
—
let checkValue = true;
@JetBrains. All rights reserved
Let
—
let checkValue = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
Type: true
@JetBrains. All rights reserved
Let
—
let checkValue = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
checkValue = false;
Type: true
@JetBrains. All rights reserved
Let
—
let checkValue = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
checkValue = false; //ok
Type: boolean
Inferred type: true
@JetBrains. All rights reserved
Let
—
let checkValue = true;
let falseValue: false = checkValue; //error
let trueValue: true = checkValue; //ok
checkValue = false; //ok
falseValue: false = checkValue; //ok
trueValue: true = checkValue; //error
Type: boolean
Inferred type: true
Inferred type: false
@JetBrains. All rights reserved
function getBoolean() {
let value: true = true;
return value;
}
Return Type
—
@JetBrains. All rights reserved
function getBoolean() {
let value: true = true;
return value;
} //: true
Type: true
Inferred type: true
Return Type
—
@JetBrains. All rights reserved
function getBoolean() {
let value = true;
return value;
}
Return Type
—
Type: boolean
Inferred type: true
@JetBrains. All rights reserved
function getBoolean() {
let value = true;
return value;
} //: boolean
Return Type
—
Type: boolean
Inferred type: true
@JetBrains. All rights reserved
function getNumber() {
let value: number | string = 1;
return value;
}
Type: number | string
Inferred type: 1
Return Type
—
@JetBrains. All rights reserved
function getNumber() {
let value: number | string = 1;
return value;
}
: 1
: number | string
Type: number | string
Inferred type: 1
Return Type
—
@JetBrains. All rights reserved
function getNumber() {
let value: number | string = 1;
return value;
}
: 1
: number
: number | string
Type: number | string
Inferred type: 1
Return Type
—
@JetBrains. All rights reserved
Return Type
—
function getNumber() {
let value: number | string = 1;
return value;
}
: 1
: number
: number | string
Return Type = Fixed(Inferred Type)
Type: number | string
Inferred type: 1
@JetBrains. All rights reserved
function getBoolean1() {
let value: true = true;
return value;
}
function getBoolean2() {
let value = true;
return value;
}
Return Type
—
@JetBrains. All rights reserved
function getBoolean1() {
let value: true = true;
return value; //: true
}
function getBoolean2() {
let value = true;
return value;
}
Return Type
—
@JetBrains. All rights reserved
function getBoolean1() {
let value: true = true;
return value; //: true
}
function getBoolean2() {
let value = true;
return value; //: true(widening)
}
Return Type
—
@JetBrains. All rights reserved
• Литеральные типы: расширяемый и нерасширяемый
• Литералы используемые в коде имеют расширяемый
тип
• При некоторые операциях типы расширяются до
соответствующих примитивных типов
Widening
Literal Types
—
@JetBrains. All rights reserved
Операции расширяющие тип:
• Вычисление возвращаемого типа функции
• Присваивание
• Вызов метода
Widening
Literal Types
—
@JetBrains. All rights reserved
Операции расширяющие тип*:
• Вычисление возвращаемого типа функции
• Присваивание
• Вызов метода
* Есть исключения
Widening
Literal Types
—
@JetBrains. All rights reserved
Afterwords
—
@JetBrains. All rights reserved
function getBoolean1() {
let value: true = true;
return value; //: true
}
function getBoolean2() {
let value = true;
return value; //: true(widening)
}
Literal Types
—
@JetBrains. All rights reserved
function getBoolean1(): boolean {
let value: true = true;
return value; //: true
}
function getBoolean2(): boolean {
let value = true;
return value; //: true(widening)
}
Literal Types
—
@JetBrains. All rights reserved
Используйте явные типы!
Widening
Literal Types
—
jetbrains.com
@JetBrains. All rights reserved
Thanks
—
@anstarovoyt
andrey.starovoyt@jetbrains.com

Weitere ähnliche Inhalte

Was ist angesagt?

JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 

Was ist angesagt? (19)

Discovering functional treasure in idiomatic Groovy
Discovering functional treasure in idiomatic GroovyDiscovering functional treasure in idiomatic Groovy
Discovering functional treasure in idiomatic Groovy
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Don't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHPDon't be STUPID, Grasp SOLID - North East PHP
Don't be STUPID, Grasp SOLID - North East PHP
 
Don't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo EditionDon't Be STUPID, Grasp SOLID - ConFoo Edition
Don't Be STUPID, Grasp SOLID - ConFoo Edition
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua LawrenceEmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in java
 
Autumn collection JavaOne 2014
Autumn collection JavaOne 2014Autumn collection JavaOne 2014
Autumn collection JavaOne 2014
 
RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!RubyConf Portugal 2014 - Why ruby must go!
RubyConf Portugal 2014 - Why ruby must go!
 
PHP7: Hello World!
PHP7: Hello World!PHP7: Hello World!
PHP7: Hello World!
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)PHP 7.0 new features (and new interpreter)
PHP 7.0 new features (and new interpreter)
 
Developing A Procedural Language For Postgre Sql
Developing A Procedural Language For Postgre SqlDeveloping A Procedural Language For Postgre Sql
Developing A Procedural Language For Postgre Sql
 
Kotlin Types for Java Developers
Kotlin Types for Java DevelopersKotlin Types for Java Developers
Kotlin Types for Java Developers
 

Ähnlich wie JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?

Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 

Ähnlich wie JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript? (20)

Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Roman Schejbal: From Madness To Reason
Roman Schejbal: From Madness To ReasonRoman Schejbal: From Madness To Reason
Roman Schejbal: From Madness To Reason
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWT
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava Schmidt
 
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Greach 2015 AST – Groovy Transformers: More than meets the eye!
Greach 2015   AST – Groovy Transformers: More than meets the eye!Greach 2015   AST – Groovy Transformers: More than meets the eye!
Greach 2015 AST – Groovy Transformers: More than meets the eye!
 
Exploring Koltin on Android
Exploring Koltin on AndroidExploring Koltin on Android
Exploring Koltin on Android
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 

Mehr von JSFestUA

Mehr von JSFestUA (20)

JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in productionJS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
 
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript PerformanceJS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
 
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
 
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
 
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
 
JS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstackJS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstack
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
 
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the ScaleJS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
 
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratchJS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
 
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотятJS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
 
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for RustJS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
 
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проектіJS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
 
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядроJS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
 
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Kürzlich hochgeladen (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 

JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?

  • 1. Старовойт Андрей Зачем нужен тип “true”? PROFESSIONAL JS CONFERENCE 8-9 NOVEMBER‘19 KYIV, UKRAINE
  • 2. @JetBrains. All rights reserved About — • Работаю в команде WebStorm 5 лет • Занимаюсь поддержкой JavaScript, TypeScript, JSX, …
  • 3. @JetBrains. All rights reserved Type “true” —
  • 4. @JetBrains. All rights reserved Type “true” — let a: true; TypeScript 2.0
  • 5. @JetBrains. All rights reserved Type “true” — let a: true; a = true; //ok a = false; //error a = 1; //error TypeScript 2.0
  • 6. @JetBrains. All rights reserved Зачем? Type “true” —
  • 7. @JetBrains. All rights reserved String Literal Overloads — function create(p: “string"):string; function create(p: "number"):number; function create(p):any; TypeScript 1.1
  • 8. @JetBrains. All rights reserved function create(p: true): string; function create(p: false): number; function create(p: boolean): string | number; Type “true” — Boolean literals in overloads
  • 9. @JetBrains. All rights reserved _ @types/node TSLSocket
  • 10. @JetBrains. All rights reserved function check(checkType?: true);Optional —
  • 11. @JetBrains. All rights reserved function check(checkType?: true); check(); Optional —
  • 12. @JetBrains. All rights reserved function check(checkType?: true); check(); check(true); Optional —
  • 13. @JetBrains. All rights reserved _ @types/babel__core
  • 14. @JetBrains. All rights reserved TypeScript 2.0 Features —
  • 15. @JetBrains. All rights reserved TypeScript 2.0 Features —
  • 16. @JetBrains. All rights reserved Type Guard —
  • 17. @JetBrains. All rights reserved class Cat { meow() } class Dog { woof() } function say(animal: Cat | Dog) { if (animal instanceof Cat) { animal.meow(); animal.woof(); } } Type Guard —
  • 18. @JetBrains. All rights reserved class Cat { meow() } class Dog { woof() } function say(animal: Cat | Dog) { if (animal instanceof Cat) { animal.meow(); //ok, no cast animal.woof(); //error } } Type Guard —
  • 19. @JetBrains. All rights reserved interface ICat { meow() } interface IDog { woof() } function say(animal: ICat | IDog) { if (animal instanceof ICat) { animal.meow(); } } Type Guard —
  • 20. @JetBrains. All rights reserved interface ICat { meow() } interface IDog { woof() } function say(animal: ICat | IDog) { if (animal instanceof ICat) { animal.meow(); } } Type Guard —
  • 21. @JetBrains. All rights reserved interface ICat { meow() } interface IDog { woof() } function say(animal: ICat | IDog) { if (animal instanceof ICat) { animal.meow(); } } //Compiled file function say(animal) { if (animal instanceof ICat) { animal.meow(); } } Type Guard —
  • 22. @JetBrains. All rights reserved Type Guard — Discriminated union types
  • 23. @JetBrains. All rights reserved interface ICat { kind: "cat"; meow() } interface IDog { kind: "dog"; woof() } function say(animal: ICat | IDog) { if (animal.kind == "cat") { animal.meow(); //ok } } Discriminated Union Types —
  • 24. @JetBrains. All rights reserved interface ICat { kind: "cat"; meow() } interface IDog { kind: "dog"; woof() } function say(animal: ICat | IDog) { if (animal.kind == "cat") { animal.meow(); //ok } } Discriminated Union Types —
  • 25. @JetBrains. All rights reserved interface ICat { kind: "cat"; meow() } interface IDog { kind: "dog"; woof() } function say(animal: ICat | IDog) { if (animal.kind == "cat") { animal.meow(); //ok } } say({ kind: "cat" }) //error Discriminated Union Types —
  • 26. @JetBrains. All rights reserved interface ICat { kind: "cat"; meow() } interface IDog { kind: "dog"; woof() } function say(animal: ICat | IDog) { if (animal.kind == "cat") { animal.meow(); //ok } } say({ kind: "cat" }) //error say({ kind: "cat", meow() {}}) //ok Discriminated Union Types —
  • 27. @JetBrains. All rights reserved Boolean literals? Discriminated Union Types —
  • 28. @JetBrains. All rights reserved type Result = { success: boolean; callback?() //if success=true } Discriminated Union Types —
  • 29. @JetBrains. All rights reserved type Result = { success: boolean; callback?() //if success=true } function process(p: Result) { p.callback(); //ok, can throw error } Discriminated Union Types —
  • 30. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; Discriminated Union Types —
  • 31. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; Discriminated Union Types —
  • 32. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { p.callback(); //error } Discriminated Union Types —
  • 33. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { if (p.success) { p.callback(); //ok } } Discriminated Union Types —
  • 34. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { if (p.success) { p.callback(); //ok } } Discriminated Union Types —
  • 35. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { if (p.success) { p.callback(); //ok } } process({success : true}) //error Discriminated Union Types —
  • 36. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { if (p.success) { p.callback(); //ok } } process({success : true}) //error process({success : true, callback() {}}) //ok Discriminated Union Types —
  • 37. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { if (p.success) { p.callback(); //ok } } process({success : true}) //error process({success : true, callback() {}}) //ok Discriminated Union Types —
  • 38. @JetBrains. All rights reserved _ @types/jsforce
  • 39. @JetBrains. All rights reserved Literal Types —
  • 40. @JetBrains. All rights reserved Literal Types — : true : false
  • 41. @JetBrains. All rights reserved Literal Types — : true : false : boolean
  • 42. @JetBrains. All rights reserved Literal Types — : true : false : boolean
  • 43. @JetBrains. All rights reserved Const — const checkValue = true;
  • 44. @JetBrains. All rights reserved Const — const checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok
  • 45. @JetBrains. All rights reserved Let — let checkValue: true = true;
  • 46. @JetBrains. All rights reserved Let — let checkValue: true = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok
  • 47. @JetBrains. All rights reserved Let — let checkValue: true = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; //error
  • 48. @JetBrains. All rights reserved Let — let checkValue = true;
  • 49. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok Type: true
  • 50. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; Type: true
  • 51. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; //ok Type: boolean Inferred type: true
  • 52. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; //ok falseValue: false = checkValue; //ok trueValue: true = checkValue; //error Type: boolean Inferred type: true Inferred type: false
  • 53. @JetBrains. All rights reserved function getBoolean() { let value: true = true; return value; } Return Type —
  • 54. @JetBrains. All rights reserved function getBoolean() { let value: true = true; return value; } //: true Type: true Inferred type: true Return Type —
  • 55. @JetBrains. All rights reserved function getBoolean() { let value = true; return value; } Return Type — Type: boolean Inferred type: true
  • 56. @JetBrains. All rights reserved function getBoolean() { let value = true; return value; } //: boolean Return Type — Type: boolean Inferred type: true
  • 57. @JetBrains. All rights reserved function getNumber() { let value: number | string = 1; return value; } Type: number | string Inferred type: 1 Return Type —
  • 58. @JetBrains. All rights reserved function getNumber() { let value: number | string = 1; return value; } : 1 : number | string Type: number | string Inferred type: 1 Return Type —
  • 59. @JetBrains. All rights reserved function getNumber() { let value: number | string = 1; return value; } : 1 : number : number | string Type: number | string Inferred type: 1 Return Type —
  • 60. @JetBrains. All rights reserved Return Type — function getNumber() { let value: number | string = 1; return value; } : 1 : number : number | string Return Type = Fixed(Inferred Type) Type: number | string Inferred type: 1
  • 61. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; } function getBoolean2() { let value = true; return value; } Return Type —
  • 62. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; //: true } function getBoolean2() { let value = true; return value; } Return Type —
  • 63. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; //: true } function getBoolean2() { let value = true; return value; //: true(widening) } Return Type —
  • 64. @JetBrains. All rights reserved • Литеральные типы: расширяемый и нерасширяемый • Литералы используемые в коде имеют расширяемый тип • При некоторые операциях типы расширяются до соответствующих примитивных типов Widening Literal Types —
  • 65. @JetBrains. All rights reserved Операции расширяющие тип: • Вычисление возвращаемого типа функции • Присваивание • Вызов метода Widening Literal Types —
  • 66. @JetBrains. All rights reserved Операции расширяющие тип*: • Вычисление возвращаемого типа функции • Присваивание • Вызов метода * Есть исключения Widening Literal Types —
  • 67. @JetBrains. All rights reserved Afterwords —
  • 68. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; //: true } function getBoolean2() { let value = true; return value; //: true(widening) } Literal Types —
  • 69. @JetBrains. All rights reserved function getBoolean1(): boolean { let value: true = true; return value; //: true } function getBoolean2(): boolean { let value = true; return value; //: true(widening) } Literal Types —
  • 70. @JetBrains. All rights reserved Используйте явные типы! Widening Literal Types —
  • 71. jetbrains.com @JetBrains. All rights reserved Thanks — @anstarovoyt andrey.starovoyt@jetbrains.com