Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Modern TypeScript: Mastering Common Patterns & ...

Modern TypeScript: Mastering Common Patterns & Types

TypeScript is JavaScript with syntax for types. TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.

TypeScript has gained traction since it first appeared in October 2012, and it has become a real game-changer in the web development world.

When used right, it becomes crucial to have a readable and easy-to-maintain codebase.

Marko Arsić

January 30, 2023
Tweet

More Decks by Marko Arsić

Other Decks in Programming

Transcript

  1. Marko Arsić Founder and CEO @ HypeTech Founder of HypeTech

    Education Independent Tech Consultant Lecturer @ ReactWeek.dev Helping companies set up teams and standardize the development process github.com/marsicdev
  2. TypeScript has gained traction since it first appeared in October

    2012, and it has become a real game-changer in the web development world
  3. TypeScript “adds” syntax to JavaScript. TypeScript is a strict superset

    of ECMAScript 2015 (aka ES6+) This syntax is used by TypeScript’s compiler to sniff out code errors before they happen, then it spits out vanilla JavaScript that browsers can understand
  4. It’s important to know all this because we need to

    know where TypeScript gets its roots in order to poke at its possible future
  5. When adding TypeScript to a project it is important that

    the developers embrace it rather than fight against it
  6. It has great features like mapped types, overloading, type inference,

    optional typing, etc, and those keep on getting better every day with incremental upgrades
  7. The language is what developers love writing. The compiler is

    what interprets the language for browsers. The service processes the language on demand with blazing speed.
  8. tsconfig.json The presence of a tsconfig.json file in a directory

    indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. JavaScript projects can use a jsconfig.json file instead, which acts almost the same but has some JavaScript-related compiler flags enabled by default.
  9. Enabling Strict Mode Without TypeScript strict mode on, the typing

    can be too lax, and that will make our codebase less type-safe. It will give the wrong impression, as some think that by adding TypeScript all typing issues are automatically fixed.
  10. Relying on Type Inference TypeScript inference is one of the

    most powerful tools of this programming language. It does all the work for us. We only have to make sure that all the pieces add together with as little intervention as possible. A crucial operator to achieving this is the typeof.
  11. It is preferable to rely on ReturnType<typeof addNumber> than adding

    the number type. By hardcoding the number type we are doing the compiler’s job. Use an appropriate syntax to express typings
  12. TypeScript even has the infer operator, which can be used

    in combination with Mapped Types to extract a type from another.
  13. Reusing interfaces When typing component interfaces, it is common to

    need to have some different interfaces variants of the same type. Those can vary in one or two parameters. A common mistake is to manually redefine those variations. That will lead to: • unnecessary boilerplate. • multiple changes are needed if one property changes in one place, that change needs to be propagated to many files.
  14. TypeScript ships with the following Mapped and Utility Types •

    Omit • Partial • Readonly • Exclude • Extract • NonNullable • ReturnType
  15. TypeScript ships with utilities, there are limited and are just

    meant to be a starting point. There are a bunch of library Type utilities that you can use and they provide battle-tested types that decrease the time you spend on writing new mappings.
  16. As all Types are removed at compile time this won’t

    increase your bundle size. Be aware that all of those types of library utilities have some requirements and restrictions.
  17. Propper Overloading TypeScript supports overloading natively. That is great as

    it can improve the readability of our contracts. However, it is different from other typed overloading languages. There are scenarios where it might make our code more complex and verbose.
  18. Avoid Function Type TypeScript ships with the Function type. It

    is like using the any keyword but for functions only. Enabling strict mode won’t prevent us from using it. Function type: • accepts any number and type of parameters. • the return type is always any
  19. Built-In Immutability TS provides all the necessary tooling to make

    sure we don’t mutate our objects. We don’t need to add heavy libraries like ImmutableJS to our codebase.
  20. Tuples One of the last additions and improvements was Tuples.

    Tuples are arrays where the number of elements is fixed. Their type is known and they are not necessarily the same type.
  21. Non-fixed size arrays with multiple types are not inferred into

    a Tuple. As the array is dynamic and might change Typescript won’t exactly know the right Type. I will return an union of all possible types.
  22. One scenario where it’s very common to find it nowadays:

    React Hooks. The Hooks implementation normally returns an array with the result plus functions, and having that array typed is nice addition to type safety .
  23. Any vs Unknown vs Never What is the difference between

    any, unknown, and never? When should we be using each one of those? What are its drawbacks and strengths?
  24. By default, when the type annotation is missing and can’t

    be inferred, the compiler will default to the any type. This is considered a bad practice and has an easy fix. We can enable strict mode on to make the above code fail.
  25. The unknown type is simple but sometimes the most tricky

    one to grasp. It is simply the parent of all types. The usage of unknown is the recommended alternative to any. It lets us define wider types whilst keeping safe type checking.
  26. One common usage of unknown is to be used as

    a bridge to bypass typings. The compiler is leveraging the typing responsibility of the developer. That means, it should be used with caution.
  27. The never is a simple but at first quite confusing

    type. It is a type to express that nothing is assignable to it. It is a type that should never occur or be assigned to. By relying on the infer and never keywords, we are saving ourselves the trouble of having to duplicate any types and to better express our interfaces.
  28. any should be avoided as much as possible in favor

    of unknown. However, it is fine to use in some situations where unknown does not work for you. The never type is useful to help us express type restrictions and identify type restrictions of the language
  29. +

  30. These guidelines are simple to follow and are meant to

    help you embrace ecosystem rather than fight it.
  31. By applying these simple tips you will have a better,

    less verbose, and easy to maintain codebase.
  32. Q & A As everything good in life, knowledge is

    great only when shared https://discord.gg/94uhCAkFKf