https://effectivetypescript.com
Effective TypeScript
Effective TypeScript: 83 Specific Ways to Improve Your TypeScript
Effective TypeScript Effective TypeScript TypeScript is a typed superset of JavaScript with the potential to solve many of the headaches for which JavaScript is famous. But TypeScript has a learning curve of its own, and understanding how to use it effectively can take time. Effective TypeScript (2nd Edition) guides you through 83 specific ways to improve your use of TypeScript, following the format popularized by Effective C++ and Effective Java. The second edition is thoroughly revised and updated to reflect the way that TypeScript is used 2024. Buy it today! Already have the Book? Visit the GitHub project to see all of the code snippets from the book in one place. You can also report any errors you've found. If you're interested in a TypeScript book talk at your company, please reach out via Twitter or email. Buy 2nd Edition Subscribe Praise for Effective TypeScript Effective TypeScript explores the most common questions we see when working with TypeScript and provides practical, results-oriented advice. Regardless of your level of TypeScript experience, you can learn something from this book. Ryan Cavanaugh, Engineering Lead for TypeScript at Microsoft This book is packed with practical recipes and must be kept on the desk of every TypeScript eveloper. Even if you think you know TypeScript already, get this book and you won't regret it. Yakov Fain, Java Champion I have been working with TypeScript for two years, and with Flow for five. And it happens that I provided technical feedback for this book. It was a joy read. The items in the book provide specific, actionable advice that will help to deepen your understanding of TypeScript, and Dan's explanations are clear and concise. There is a lot of useful information, but my favorite part is Chapter 4, Type Design. Even as an experienced hotshot I learned a number of new things. And the advice sticks with me in my day-to-day work. For example I make an effort to apply types to entire function expressions, and in some cases I do so by using specialized React event handler types that this book pointed me to. Plus Dan convinced me to switch my @type dependencies to devDependencies. Jesse Hallett, Senior Software Engineer, Originate, Inc. The book hit me in exactly the right spot. I'm an experienced developer and I've worked with JS on and off for many years, but my structured TS education is limited to the official tutorial. I was able to figure out most of it along the way (TS is intuitive if you have good JS knowledge and realize how it works, Google and SO helped a lot too), but this approach also left me with a lot of gaps in my knowledge, many of which I don't even realize I have. This book excels at plugging such gaps. Now I have to go and refactor some of my code in the light of what I've learned. Matěj Zábský Read more reviews on Goodreads and Amazon. Recent Blog Posts See All Posts. Item 74: Know How to Reconstruct Types at Runtime Thu 31 October 2024 A fundamental part of TypeScript's design is that TypeScript types are erased at runtime. There's no way to access them. But inevitably, you'll want to do just that. This comes up most often when you want to validate that user input matches a TypeScript type. Faced with this problem, TypeScript developers often reach for Zod, a schema validation tool. But Zod has some downsides, and it's not the only solution to this conundrum. This sample item explores this problem and three possible solutions to it. Continue reading » Notes on TypeScript 5.6 Mon 30 September 2024 We TypeScript developers are a lucky bunch. While some languages (Python, JavaScript) are released annually, every three years (C++) or even less, we get four new versions of TypeScript every year. TypeScript 5.6 was released on September 9th, 2024. Let's take a look. Continue reading » A keyof puzzle Fri 30 August 2024 Effective TypeScript is nearly 400 pages long, but I've received the most feedback by far on just one passage. It comes in Item 7: Think of Types as Sets of Values: keyof (A&B) = (keyof A) | (keyof B)keyof (A|B) = (keyof A) & (keyof B) If you can build an intuition for why these equations hold, you'll have come a long way toward understanding TypeScript's type system! I'll explain these equations in a moment. But before I do, head over to the TypeScript Playground and test them out with a few types. See if you can build that intuition for why they hold. Continue reading » A TypeScripter's Take on Zig (Advent of Code 2023) Wed 17 July 2024 What can Zig learn from TypeScript, and what can TypeScript learn from Zig? Continue reading » TypeScript 5.5: A Blockbuster Release Tue 02 July 2024 We TypeScript developers are a lucky bunch. While some languages (Python, JavaScript) are released annually, every three years (C++) or even less, we get four new versions of TypeScript every year. TypeScript 5.5 was released on June 20th, 2024, and it was a real blockbuster. Let's take a look. Continue reading » Item 36: Use a Distinct Type for Special Values Thu 13 June 2024 It's tempting to use "", 0 or -1 as special values: an empty string might represent text that hasn't loaded yet, or -1 could stand in for a missing number. In TypeScript, this is almost always a bad idea. Special values need to be handled specially, and giving them a distinct type, such as null, allows TypeScript to enforce that you do so. Continue reading » Now Available: Effective TypeScript, Second Edition Tue 21 May 2024 Fully updated, thoroughly revised, now with 50% more book! Continue reading » The Making of a TypeScript Feature: Inferring Type Predicates Tue 16 April 2024 Over the past few months I became a TypeScript contributor and implemented a new feature, type predicate inference, that should be one of the headliners for TypeScript 5.5. This post tells the story of how that happened: why I wanted to contribute to TypeScript, the journey to implementing the feature and getting the PR merged, and what I've learned along the way. This is not a short read, but it will give you a good sense of what it's like to become a TypeScript contributor and develop a new feature. Continue reading » Flow Nodes: How Type Inference Is Implemented Sun 24 March 2024 If a variable gets a type but no one looks at it, does it really get a type at all? This post looks at how type inference is implemented in the TypeScript compiler. It's of some interest to anyone who uses TypeScript and is curious how it works, but it will be most relevant to developers who want to contribute to TypeScript itself. Continue reading » The Hidden Side of Type Predicates Tue 27 February 2024 Type guards are a powerful tool for improving TypeScript's built-in control flow analysis. This post looks at when it's appropriate to use a type predicate, and in particular what it means when a type predicate returns false. Continue reading » Older Posts 2024-01-31 Effective TypeScript Talk at Etsy (Dec 2020) 2023-12-31 Don't Write Traditional Getter and Setter Methods in JavaScript and TypeScript 2023-11-29 Using infer to unpack nested types 2023-10-27 Overload on the type of this to specialize generics (The Lost Item) 2023-09-27 The Saga of the Closure Compiler, and Why TypeScript Won 2023-08-29 TypeScript and SQL: Six Ways to Bridge the Divide 2023-07-29 Recommendation Update: ✂️ Use knip to detect dead code and types 2023-06-27 Notes on TypeScript 5.1 2023-05-31 Item 30: Don’t Repeat Type Information in Documentation 2023-04-27 A first look at Deno through the Advent of Code 2022 2023-02-07 Notes on TypeScript 5.0 beta 2022-12-25 All I Want for Christmas Is… These Seven TypeScript Improvements 2022-07-30 What's TypeScript compiling? Use a treemap to find out. 2022-05-28 A new way to test types 2022-04-18 My Twitch Debut (eslint-plugin-expect-type with Josh Goldberg) 2022-02-25 The display of types 2022-02-06 A TypeScript Perspective on Go: the 2021 Advent of Code 2021-12-10 TypeScript Types: The First 500 Years (tsconf 2021 talk) 2021-11-11 Exclusive Or and the Optional never Trick 2021-06-03 In defense of interface: Using declaration merging to disable "bad parts" 2021-05-06 The Seven Sources of Unsoundness in TypeScript 2021-04-09 The trouble with Jsonify: Unify types instead of modeling small differences 2021-03-24 Advent of Code 2020, this time in Rust 2021-02-03 Four words to avoid in TypeScript writing 2021-01-20 Generic Tips Part 3: Avoid Repeating Type Expressions 2021-01-09 Top Posts of 2020 2020-12-09 Generic Tips Part 2: Intersect what you have with whatever TypeScript wants 2020-12-04 Generic Tips Part 1: Use Classes and Currying to create new inference sites 2020-11-05 TypeScript Splits the Atom! 2020-10-20 Finding dead code (and dead types) in TypeScript 2020-10-01 Repeat yourself a little less: Strategies for mitigating prop drilling with React and TypeScript 2020-09-10 TypeScript Exercises 2020-08-12 The Golden Rule of Generics 2020-07-27 Writing a safe querySelector: the one-way street from values to types 2020-06-30 Type-safe blogs and books with literate-ts 2020-06-16 Use typed identity functions to guide type inference 2020-05-26 Item 54: Know How to Iterate Over Objects 2020-05-12 Unionize and Objectify: A Trick for Applying Conditional Types to Objects 2020-04-28 Item 19: Avoid Cluttering Your Code with Inferable Types 2020-04-09 What's the type of JSON.parse(JSON.stringify(x))? 2020-03-24 Item 31: Push Null Values to the Perimeter of Your Types 2020-03-09 Item 41: Understand Evolving any 2020-03-06 Welcome to Effective TypeScript! For new TypeScript content every ~month, including new examples, sample items, videos and book updates, choose one of these ways to stay in touch: Subscribe to the Newsletter Follow @danvdk RSS Table of Contents In an Effective-style book, the title of each item is a specific piece of advice. This means that the Table of Contents forms a summary of all the advice in the book. If any item piques your curiosity and you want to learn more, order a copy. Chapter 1: Getting to Know TypeScriptBefore we dive into the details, this chapter helps you understand the big picture of TypeScript. What is it and how should you think about it? How does it relate to JavaScript? Are its types nullable or are they not? What's this about any? And ducks? Understand the Relationship Between TypeScript and JavaScript Know Which TypeScript Options You're Using Understand That Code Generation Is Independent of Types Get Comfortable with Structural Typing Limit Use of the any Type Chapter 2: TypeScript’s Type SystemThis chapter walks you through the nuts and bolts of TypeScript's type system: how to think about it, how to use it, choices you'll need to make, and features you should avoid. TypeScript's type system is surprisingly powerful and able to express things you might not expect a type system to be able to. The items in this chapter will give you a solid foundation to build upon as you write TypeScript and read the rest of this book. Use Your Editor to Interrogate and Explore the Type System Think of Types as Sets of Values Know How to Tell Whether a Symbol Is in the Type Space or Value Space Prefer Type Annotations to Type Assertions Avoid Object Wrapper Types (String, Number, Boolean, Symbol, BigInt) Distinguish Excess Property Checking from Type Checking Apply Types to Entire Function Expressions When Possible Know the Differences Between type and interface Use readonly to Avoid Errors Associated with Mutation Use Type Operations and Generic Types to Avoid Repeating Yourself Prefer More Precise Alternatives to Index Signatures Avoid Numeric Index Signatures Chapter 3: Type InferenceThis chapter shows you some of the problems that can arise with type inference and how to fix them. After reading it, you should have a good understanding of how TypeScript infers types, when you still need to write type declarations, and when it's a good idea to write type declarations even when a type can be inferred. Avoid Cluttering Your Code with Inferable Types Use Different Variables for Different Types Understand How a Variable Gets Its Type Create Objects All at Once Understand Type Narrowing Be Consistent in Your Use of Aliases Understand How Context Is Used in Type Inference Understand Evolving Types Use Functional Constructs and Libraries to Help Types Flow Use async Functions Instead of Callbacks to Improve Type Flow Use Classes and Currying to Create New Inference Sites Chapter 4: Type DesignCode is difficult to understand if you can't see the data or data types on which it operates. This is one of the great advantages of a type system: by writing out types, you make them visible to readers of your code. And this makes your code understandable. Other chapters cover the nuts and bolts of TypeScript types: using them, inferring them, and writing declarations with them. This chapter discusses the design of the types themselves. The examples in this chapter are all written with TypeScript in mind, but most of the ideas are more broadly applicable. Prefer Types That Always Represent Valid States Be Liberal in What You Accept and Strict in What You Produce Don’t Repeat Type Information in Documentation Avoid Including null or undefined in Type Aliases Push Null Values to the Perimeter of Your Types Prefer Unions of Interfaces to Interfaces with Unions Prefer More Precise Alternatives to String Types Use a Distinct Type for Special Values Limit the Use of Optional Properties Avoid Repeated Parameters of the Same Type Prefer Unifying Types to Modeling Differences Prefer Imprecise Types to Inaccurate Types Name Types Using the Language of Your Problem Domain Avoid Types Based on Anecdotal Data Chapter 5: Unsoundness and the any TypeType systems were traditionally binary affairs: either a language had a fully static type system or a fully dynamic one. TypeScript blurs the line, because its type system is optional and gradual. You can add types to parts of your program but not others. This is essential for migrating existing JavaScript codebases to TypeScript bit by bit. Key to this is the any type, which effectively disables type checking for parts of your code. It is both powerful and prone to abuse. Learning to use any wisely is essential for writing effective TypeScript. This chapter walks you through how to limit the downsides of any while still retaining its benefits. Use the Narrowest Possible Scope for any Types Prefer More Precise Variants of any to Plain any Hide Unsafe Type Assertions in Well-Typed Functions Use unknown Instead of any for Values with an Unknown Type Prefer Type-Safe Approaches to Monkey Patching Avoid Soundness Traps Track Your Type Coverage to Prevent Regressions in Type Safety Chapter 6: Generics and Type-Level ProgrammingTypeScript's type system is designed to model the runtime behavior of JavaScript code. Because JavaScript is so dynamic and permissive, this has pushed TypeScript's type system to develop increasingly powerful capabilities. This includes logic for mapping between types. When you add generic type aliases to the mix, TypeScript's type system becomes powerful enough that you can think of it as its own independent programming language. This chapter will help you decide whether it's necessary to use generic types and presents some alternatives. Used well, type-level code can improve other developers' experiences without their ever needing to know that there's fancy type-level code involved. Think of Generics as Functions Between Types Avoid Unnecessary Type Parameters Prefer Conditional Types to Overload Signatures Know How to Control the Distribution of Unions over Conditional Types Use Template Literal Types to Model DSLs and Relationships Between Strings Write Tests for Your Types Pay Attention to How Types Display Prefer Tail-Recursive Generic Types Consider Codegen as an Alternative to Complex Types Chapter 7: TypeScript RecipesAs the TypeScript community has grown, developers have come up with more and more tricks for solving specific problems. Some of these "recipes" leverage TypeScript's type checker to catch new categories of mistakes, such as values getting out of sync or nonexhaustive conditionals. Others are tricks for modeling patterns that TypeScript struggles with on its own: iterating over objects, filtering null values from Arrays, or modeling variadic functions. By applying the recipes in this chapter, you'll help TypeScript catch more real problems with fewer false positives. Use never Types to Perform Exhaustiveness Checking Know How to Iterate Over Objects Use Record Types to Keep Values in Sync Use Rest Parameters and Tuple Types to Model Variadic Functions Use Optional never Properties to Model Exclusive Or Consider Brands for Nominal Typing Chapter 8: Type Declarations and @typesDependency management can be confusing in any language, and TypeScript is no exception. This chapter will help you build a mental model for how dependencies work in TypeScript and show you how to work through some of the issues that can come up with them. It will also help you craft your own type declaration files to publish and share with others. By writing great type declarations, you can help not just your own project but the entire TypeScript community. Put TypeScript and @types in devDependencies Understand the Three Versions Involved in Type Declarations Export All Types That Appear in Public APIs Use TSDoc for API Comments Provide a Type for this in Callbacks if It's Part of Their API Mirror Types to Sever Dependencies Use Module Augmentation to Improve Types Chapter 9: Writing and Running Your CodeThis chapter is a bit of a grab bag: it covers some issues that come up in writing code (not types) as well as issues you may run into when you run your code. Prefer ECMAScript Features to TypeScript Features Use Source Maps to Debug TypeScript Know How to Reconstruct Types at Runtime Understand the DOM Hierarchy Create an Accurate Model of Your Environment Understand the Relationship Between Type Checking and Unit Testing Pay Attention to Compiler Performance Chapter 10: Modernization and MigrationYou've heard that TypeScript is great. You also know from painful experience that maintaining your 15-year-old, 100,000-line JavaScript library isn't. If only it could become a TypeScript library! This chapter offers some advice about migrating your JavaScript project to TypeScript without losing your sanity and abandoning the effort. Write Modern JavaScript Use @ts-check and JSDoc to Experiment with TypeScript Use allowJs to Mix TypeScript and JavaScript Convert Module by Module Up Your Dependency Graph Don't Consider Migration Complete Until You Enable noImplicitAny About the Author Dan Vanderkam is an independent software developer based in upstate New York. He was previously a principal software engineer at Sidewalk Labs and a senior staff software engineer at Google. He also worked on open source genome visualizations at Mount Sinai's Icahn School of Medicine, as well as on Google search features used by billions of people (search for sunset nyc or population of france). He has a long history of working on open source projects, including the popular dygraphs library and source-map-explorer, a tool for visualizing JavaScript code size. When he's not programming, Dan enjoys rock climbing at the nearby Shawangunk Ridge, hiking in the Catskills, and birdwatching all around the world. He also writes on Medium and at danvk.org. He earned his bachelor's in Computer Science from Rice University in Houston, Texas, and lives in Wallkill, New York. Follow @danvdk Subscribe © 2019 - 2024 Dan Vanderkam Powered by Hexo
https://effectivetypescript.com
Editeu el vostre lloc?
Què estàs fent?