Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

47 views

Published on

Литеральные типы в TypeScript, которые появились несколько лет назад, на самом деле произвели мини-революцию в языке, которую многие не заметили. Сегодня сложно представить себе TypeScript без этих типов и механизмов, построеных поверх них: mapped, indexer, keyof types и многие другие. В докладе я расскажу, как и почему литеральные типы появились в TypeScript и какие концепции они привнесли в язык. Поговорим также о том, почему с точки зрения разработчика анализатора TypeScript литеральные типы — это по-настоящему сложная языковая фича. Ну и конечно коснемся вопроса, как это все согласуется с реальным миром, а именно с JavaScript.

Published in: Education
  • Be the first to comment

  • Be the first to like this

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

  1. 1. Старовойт Андрей Зачем нужен тип “true”? PROFESSIONAL JS CONFERENCE 8-9 NOVEMBER‘19 KYIV, UKRAINE
  2. 2. @JetBrains. All rights reserved About — • Работаю в команде WebStorm 5 лет • Занимаюсь поддержкой JavaScript, TypeScript, JSX, …
  3. 3. @JetBrains. All rights reserved Type “true” —
  4. 4. @JetBrains. All rights reserved Type “true” — let a: true; TypeScript 2.0
  5. 5. @JetBrains. All rights reserved Type “true” — let a: true; a = true; //ok a = false; //error a = 1; //error TypeScript 2.0
  6. 6. @JetBrains. All rights reserved Зачем? Type “true” —
  7. 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. 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. 9. @JetBrains. All rights reserved _ @types/node TSLSocket
  10. 10. @JetBrains. All rights reserved function check(checkType?: true);Optional —
  11. 11. @JetBrains. All rights reserved function check(checkType?: true); check(); Optional —
  12. 12. @JetBrains. All rights reserved function check(checkType?: true); check(); check(true); Optional —
  13. 13. @JetBrains. All rights reserved _ @types/babel__core
  14. 14. @JetBrains. All rights reserved TypeScript 2.0 Features —
  15. 15. @JetBrains. All rights reserved TypeScript 2.0 Features —
  16. 16. @JetBrains. All rights reserved Type Guard —
  17. 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. 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. 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. 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. 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. 22. @JetBrains. All rights reserved Type Guard — Discriminated union types
  23. 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. 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. 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. 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. 27. @JetBrains. All rights reserved Boolean literals? Discriminated Union Types —
  28. 28. @JetBrains. All rights reserved type Result = { success: boolean; callback?() //if success=true } Discriminated Union Types —
  29. 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. 30. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; Discriminated Union Types —
  31. 31. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; Discriminated Union Types —
  32. 32. @JetBrains. All rights reserved type Result = { success: true, callback() } | { success: false }; function process(p: Result) { p.callback(); //error } Discriminated Union Types —
  33. 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. 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. 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. 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. 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. 38. @JetBrains. All rights reserved _ @types/jsforce
  39. 39. @JetBrains. All rights reserved Literal Types —
  40. 40. @JetBrains. All rights reserved Literal Types — : true : false
  41. 41. @JetBrains. All rights reserved Literal Types — : true : false : boolean
  42. 42. @JetBrains. All rights reserved Literal Types — : true : false : boolean
  43. 43. @JetBrains. All rights reserved Const — const checkValue = true;
  44. 44. @JetBrains. All rights reserved Const — const checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok
  45. 45. @JetBrains. All rights reserved Let — let checkValue: true = true;
  46. 46. @JetBrains. All rights reserved Let — let checkValue: true = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok
  47. 47. @JetBrains. All rights reserved Let — let checkValue: true = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; //error
  48. 48. @JetBrains. All rights reserved Let — let checkValue = true;
  49. 49. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok Type: true
  50. 50. @JetBrains. All rights reserved Let — let checkValue = true; let falseValue: false = checkValue; //error let trueValue: true = checkValue; //ok checkValue = false; Type: true
  51. 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. 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. 53. @JetBrains. All rights reserved function getBoolean() { let value: true = true; return value; } Return Type —
  54. 54. @JetBrains. All rights reserved function getBoolean() { let value: true = true; return value; } //: true Type: true Inferred type: true Return Type —
  55. 55. @JetBrains. All rights reserved function getBoolean() { let value = true; return value; } Return Type — Type: boolean Inferred type: true
  56. 56. @JetBrains. All rights reserved function getBoolean() { let value = true; return value; } //: boolean Return Type — Type: boolean Inferred type: true
  57. 57. @JetBrains. All rights reserved function getNumber() { let value: number | string = 1; return value; } Type: number | string Inferred type: 1 Return Type —
  58. 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. 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. 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. 61. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; } function getBoolean2() { let value = true; return value; } Return Type —
  62. 62. @JetBrains. All rights reserved function getBoolean1() { let value: true = true; return value; //: true } function getBoolean2() { let value = true; return value; } Return Type —
  63. 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. 64. @JetBrains. All rights reserved • Литеральные типы: расширяемый и нерасширяемый • Литералы используемые в коде имеют расширяемый тип • При некоторые операциях типы расширяются до соответствующих примитивных типов Widening Literal Types —
  65. 65. @JetBrains. All rights reserved Операции расширяющие тип: • Вычисление возвращаемого типа функции • Присваивание • Вызов метода Widening Literal Types —
  66. 66. @JetBrains. All rights reserved Операции расширяющие тип*: • Вычисление возвращаемого типа функции • Присваивание • Вызов метода * Есть исключения Widening Literal Types —
  67. 67. @JetBrains. All rights reserved Afterwords —
  68. 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. 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. 70. @JetBrains. All rights reserved Используйте явные типы! Widening Literal Types —
  71. 71. jetbrains.com @JetBrains. All rights reserved Thanks — @anstarovoyt andrey.starovoyt@jetbrains.com

×