O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Антихрупкий TypeScript | Odessa Frontend Meetup #17

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Próximos SlideShares
C++ references
C++ references
Carregando em…3
×

Confira estes a seguir

1 de 60 Anúncio

Антихрупкий TypeScript | Odessa Frontend Meetup #17

Baixar para ler offline

Скомпилировалось — значит работает. К сожалению это выражение не про typescript. Кажется, что количество рантайм ошибок спровоцированных несоответствием типов должно стать меньше, однако компилятор ts не помогает разработчику писать качественный код, а наоборот поощряет использование грязных хаков. Филипп Сапронов рассказывает, как прекратить войну с компилятором и писать более надёжный код, используя всю мощь системы типов. Доклад будет интересен тем, кому ts кажется простым или наоборот сложным, а также тем, кто хочет научится понимать код тайпингов таких библиотек как lodash.

Скомпилировалось — значит работает. К сожалению это выражение не про typescript. Кажется, что количество рантайм ошибок спровоцированных несоответствием типов должно стать меньше, однако компилятор ts не помогает разработчику писать качественный код, а наоборот поощряет использование грязных хаков. Филипп Сапронов рассказывает, как прекратить войну с компилятором и писать более надёжный код, используя всю мощь системы типов. Доклад будет интересен тем, кому ts кажется простым или наоборот сложным, а также тем, кто хочет научится понимать код тайпингов таких библиотек как lodash.

Anúncio
Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a Антихрупкий TypeScript | Odessa Frontend Meetup #17 (20)

Anúncio

Mais de OdessaFrontend (20)

Mais recentes (20)

Anúncio

Антихрупкий TypeScript | Odessa Frontend Meetup #17

  1. 1. Antifragile< > Philipp Sapronov philipp.sapronov@gmail.com
  2. 2. Antifragility is a property of systems in which they increase in capability to thrive as a result of stressors, shocks, volatility, noise, mistakes, faults, attacks, or failures.
  3. 3. Developers
  4. 4. Strict Structural Turing Complete Type system is:
  5. 5. Strict
  6. 6. " ": , strict // "noImplicitAny": true, // "strictNullChecks": true, // "strictFunctionTypes": true, // "strictBindCallApply": true, // "strictPropertyInitialization": true, // "noImplicitThis": true, // "alwaysStrict": true, true Strict
  7. 7. A Note on Soundness TypeScript’s type system allows certain operations that can’t be known at compile-time to be safe. When a type system has this property, it is said to not be “sound”. {...} https://www.typescriptlang.org/docs/handbook/type-compatibility.html Strict
  8. 8. Strict any Strict
  9. 9. unknown ts before try catch {} ( : ) {} e any ts v4.0+ try catch {} ( : ) {} e unknown Strict
  10. 10. const : [] = [] [ ]. () arr arr string 0 split // error Strict
  11. 11. /* tsconfig.json */ // v4.1+ " ": , noUncheckedIndexedAccess true Strict
  12. 12. // "noUncheckedIndexedAccess": true, // string | undefined const : [] = [] [ ] arr arr string 0 Strict
  13. 13. A B | Union type T1 = | string number T1: string | number type T2 = | {a: string} {b: number} T2: {a: string} | {b: number} Strict
  14. 14. interface const return User User user { ?: ; } = ( : ) => { .email. (); } email string | null getEmail toLowerCase user Strict
  15. 15. ( .email ). (); user as string toLowerCase Strict
  16. 16. Casting ( ).method() null as any A as B (( ...) ...) null as as Strict
  17. 17. About narrowing (guards) typescriptlang.org/docs/handbook/2/narrowing.html Strict
  18. 18. Strict // typeof type guards /*...*/ // instanceof narrowing /*...*/ // The “in” operator narrowing /*...*/ // Using type predicates if if instanceof if in function is (typeof “ ”) { } ( ) { } (“ ” ) { } ( : ): str x Date x Shape Circle === string property isCircle shape shape
  19. 19. Structural
  20. 20. interface const const => { : ; : ; }; = : , : ; = ( : ) {}; ( ); ( : , : ); Point point: Point fn point Point fn point fn x y x y x y number number 100 100 100 100 { } { } // OK // OK Structural
  21. 21. const => const = ( : : , : ) {}; = : , : ; ( ); fn point point fn point { } { } x y x y z number number 1.5 2.4, : 999999 // OK Structural
  22. 22. const const : , : ; . ( ). (( ) => { = [ ]; }); point point value point = x y Object { } 1.5 2.4 keys forEach key key /** * Element implicitly has an 'any' type because expression of type 'string' * can't be used to index type '{ x: number; y: number; }'. */ Structural
  23. 23. // lib.es5.d.ts // proposal < > keys keys ( : ): [] ( : T): ( )[] o o object string object T T extends keyof Structural
  24. 24. type function for const of if === === return throw new const = : ; : ( : ) { ( . ) { ( " " || " ") ; (" "); } } = : , : , ( ); Point Point key key key Error point point { } { } x y Object ( ) x y z number number ; x y This is impossible 0.5 2.4 : 999999999 fn keys fn point point // (x | y)[] // Throws an exception https://stackoverflow.com/questions/55012174/why-doesnt-object-keys-return-a-keyof-type-in-typescript Structural
  25. 25. Branding and Type-Tagging Structural
  26. 26. const bar bar bar bar bar bar = Object { } foo “ ” : ; . ( , , , , ) bar assign // any Structural
  27. 27. // lib.es5.d.ts assign assign assign assign < , >( : , : ): & ; < , , >( : , : , : ): & & ; < , , , >( : , : , : , : ): & & & ; ( : , : []): ; T U target source T U V target source1 source2 T U V W target source1 source2 source3 target sources T U T U T U V T U V T U V W T U V W object ... any any Structural
  28. 28. A B & Intersection type T1 = & string number T1: never type T2 = & {a: string} {b: number} T2: {a: string, b: number} Structural
  29. 29. // X | Y | Z => X & Y & Z type = extends ? => : extends => ? : UnionToIntersection U U : U : I I ; < > infer ( k ) (k ) any void never void never ( ) assign< , []>( : , : ): & < [ ]>; T P T P T UnionToIntersection P extends extends object object number t sources ... Structural
  30. 30. TypeScript Structural
  31. 31. Turing Complete
  32. 32. Generic Types Conditional Types Recursive Types Mapped Types Turing complete
  33. 33. Cup<T> Turing complete
  34. 34. < > = T * type Turing complete
  35. 35. type < > Identity T T = type < , > [ , ] Pair T U T U = const => ( ) identity t t = const => ( , ) [ , ] pair t u t u =
  36. 36. function => const < > ( : | (() )): [ , < < >>]; [ , ] < | >( ) ( ) useState Dispatch SetStateAction state setState useState setState S S S S S initialState null = string null /* only string or null is allowed */ Turing complete
  37. 37. type type extends => const extends => return { : }; < > = { : []; : ( : ) ; }; = < >( : < >) { { } ; }; Row TableProps T Row T T T Row TableProps T = id rows onClick void string row props Table < > </ > table table /* ... */ Turing complete
  38. 38. interface extends const extends => const return < . < >> { : ; : < >; } = <T . < >>( : < >) { { : , } ; { } ; }; Props T React ComponentType T React.ComponentProps T React ComponentType Props T component Component componentProps props componentProps any component componentProps any = Item props < /> Component ... ? Turing complete
  39. 39. Conditional types Turing complete
  40. 40. ? : === typeof a “ ” boolean true false Turing complete
  41. 41. ? : extends A boolean true false ? : === typeof a “ ” boolean true false
  42. 42. * ? : extends A B * Turing complete
  43. 43. never ? : extends T U T type Exclude<T, U> = Exclude< | , > 'username' 'email' 'email' // username Turing complete
  44. 44. infer Turing complete
  45. 45. type extends ? : type type < > < > ; < []>; <[ ]>; ArrayType T T Array T1 ArrayType T2 ArrayType = U U never = string = string, number infer // string // string | number Turing complete
  46. 46. type extends ? : type < > < > < > ; < < | < < < >>>>>; ArrayType T T Array ArrayType T2 ArrayType Array Array Array Array = U U never = string number infer // string | number Turing complete // v4.1+
  47. 47. type extends keyof extends ? : extends keyof ? : < . | < >> . < > . . [ ] {}; ComponentProps T JSX IntrinsicElements JSXElementConstructor T React JSXElementConstructor T JSX IntrinsicElements JSX IntrinsicElements T any = P P infer Turing complete
  48. 48. interface extends const extends => const return < . < >> { : ; : < >; } = <T . < >>( : < >) { { : , } ; { } ; }; Props T React ComponentType T React.ComponentProps T React ComponentType Props T component Component componentProps props componentProps any component componentProps any = Item props < /> Component ... Turing complete
  49. 49. type keyof type extends type extends Component JSX IntrinsicElements JSXElementConstructor OptionalProps T T Props T Component T React.ComponentProps T OptionalProps T = any = errorMessage any component componentProps . | < > < > ‘ ’; ? { : } : {}; < < >> { : ; : < >; } & < >; input string Turing complete
  50. 50. Mapped types Turing complete
  51. 51. interface const => const => const { : ; : ; : ; } ( : ) { }; () { [ , ] = < >( ); }; SignUpData SignUpData state setState useState SignUpData email password username = = string string string // api/auth /* ... */ // components/auth signUp SignUpForm data {} Turing complete
  52. 52. interface const => const => const { : ; : ; : ; } ( : ) { }; () { [ , ] = < < >>( ); }; SignUpData SignUpData state setState useState Partial SignUpData email password username = = string string string // api/auth /* ... */ // components/auth signUp SignUpForm data {} Turing complete
  53. 53. { } email password username : , : , : string string string { } email password username ?: , ?: , ?: string string string Turing complete
  54. 54. { } [ ] in : K * * Turing complete
  55. 55. type Partial<T> = { } [ ] in ?: K keyof T T[K] Turing complete
  56. 56. type Required<T> = { } [ ]- in ?: K keyof T T[K] Turing complete
  57. 57. Exclude Extract Pick Omit Partial ReturnType Parameters Challenge :) Turing complete
  58. 58. Links www.typescriptlang.org @why_typescript_is_bad freecodecamp.org/news/typescript-curry-ramda-types-f747e99744ab ybogomolov.me/typesafe-typescript github.com/type-challenges/type-challenges github.com/millsp/ts-toolbelt
  59. 59. Thank s!

×