TypeScript Survival Guide: Life-Saving Tips and Techniques

Rate this content
Bookmark

Let's go through your survival kit for the TS jungle! In this talk, you'll get the complete TS guide from simple tips to complex techniques that will help you take the most of TypeScript not only in those large production projects, but also in your small hobby idea. We'll explore validations, configuration, typings and much more.

This talk has been presented at TypeScript Congress 2023, check out the latest edition of this Tech Conference.

FAQ

Tsconfig-basis is an official repository containing several TypeScript configuration bases that you can extend naturally using the 'extends' property in your tsconfig file. This allows for easy reuse of configurations without repetitive copying and pasting.

Rendered types in TypeScript are used to specify more specific string types, such as marking a string as an ID to prevent incorrect type assignments. These types are useful in ensuring that only the correct form of a string is used in specific contexts.

Type guards and assertion functions are TypeScript features used to narrow down the type of variables without explicit casting. Type guards return a boolean indicating if a variable is a certain type, while assertion functions throw an error if a variable is not of a specified type.

Enums in TypeScript allow for the definition of a set of named constants, which can be either numeric or string values. They help standardize code and ensure that only predefined values are used, reducing errors and improving code readability.

In TypeScript 5.2, the 'using' keyword is introduced for managing resource disposal and memory cycles. It is used with objects that have a 'dispose' or 'async dispose' method to automatically handle resource cleanup, simplifying object lifecycle management.

The 'unknown' type in TypeScript is used as a safer alternative to 'any' for types that are not yet known, particularly in legacy systems. It allows any value to be assigned to 'unknown', but prevents 'unknown' from being assigned to other types without proper type checking.

The case conversion utility type in TypeScript is a method to convert string types between different casing styles, like snake case to camel case. It helps unify API interactions across different services by standardizing key formats without duplicating interface definitions.

Lucas Santos
Lucas Santos
7 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Hello, I'm Lucas, a software engineer at Klarna in Sweden. I will be sharing my best tips and tricks with TypeScript. One useful tool is tsconfig-basis, which eliminates the need for copying and pasting the same tsconfig file. Rendered types in TypeScript are powerful for handling different types of strings, and type guards and assertion functions make them even more useful. Enums in TypeScript can be number, string, or const, each with its own advantages and limitations. Lastly, there are new features in PS 5.2 like 'using' for resource disposal and 'unknown' for data protection, as well as a case conversion utility type for interfaces.

1. Introduction to TypeScript and tsconfig-basis

Short description:

Hello, I'm Lucas. I'm a software engineer here at Klarna in Sweden. I will be presenting the best tips and tricks that I've learned with TypeScript in these past years with you. First thing, over the past few years, I lost how many times I have copied and pasted the same tsconfig over and over again, until I discovered that I could just use tsconfig-basis. It's an official repository that has several tsconfig-basis for you to extend naturally.

Hello, I'm Lucas. I'm a software engineer here at Klarna in Sweden. I'm originally from Brazil and have been coding for the past 11 years and sharing what I learned. So if you like this talk and have any feedback, please reach out to me and my socials, just put the name of the network in elsantos.dev and you'll get there, or just elsantos.dev will also do the trick.

But cutting to the chase, I will be presenting the best tips and tricks that I've learned with TypeScript in these past years with you. And all of this in 10 minutes or less. So, let's go.

First thing, over the past few years, I lost how many times I have copied and pasted the same tsconfig over and over again, until I discovered that I could just use tsconfig-basis. It's an official repository that has several tsconfig-basis for you to extend naturally. And tsconfig supports that through the extends property. So, as you can see, we can use the extends and pass the name of the repo following the configuration that we want to extend. And if you don't like any of those configs, you can just override it by writing it again in the bottom. But this is not only for the tsconfig-basis extension. So, you can actually extend if you have local files, if you want to extend, like in a mono-repo configuration where you need to extend the base file. So, what you can do is you just need to put that path in that file, and it's magic. So, you never have to copy a tsconfig again.

2. Rendered Types and Type Guards

Short description:

Rendered types in TypeScript are powerful for handling different types of strings. They allow you to mark a string as a specific type, such as an ID, preventing mistakes like passing a name to an ID. However, rendered types require explicit type casting, which can be cumbersome. To overcome this, we have type guards and assertion functions. Type guards allow us to narrow down the type without explicit casting, while assertion functions throw errors if the type is incorrect. This makes rendered types more useful and allows for lightweight guards.

For the second tip, I wanted to something that took me some time to understand how powerful it actually was. I'm talking about rendered types. Normally, you don't see a lot of those in TS Code. That's because they have a very specific use case. And those are massively helpful when you have different types of strings, but still strings, like a uid. You can render type to mark it as an ID, even though it's a string. But it's a string of a certain type, making it impossible to pass a name to an ID by mistake, for example. Or even to pass the wrong type of ID to some function.

However, rendered types can only be converted to explicit type casting, which is bad, so we can make a function to explicitly convert one type into another. But it's still, there's a better way to do this. And I present to you the third survival tip, the type guards and assertion functions. When you use rendered types, they are usually followed by one of those two. Because guards and assertion allows us to narrow down the type without having to explicitly cast it. I can explicitly cast anything to an ID and it's going to work, basically. The trick here is basically to add a new function that will guard the type, and this function is saying that a type is of another type as a return annotation. This way, we can do an if check and actually check the ID is an id with the rejects. But this is not just adding noise, this if there. I don't like it. This is why we have assertion functions. They are declared by saying that the function asserts a parameter of a given type. So, the main difference between one and the other is that the assertion functions don't return anything they throw, while the guards return booleans. So, this way, rendered types can be more useful, and you can also create guards that are lightweight.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Alex introduces tRPC, a toolkit for making end-to-end type-safe APIs easily, with auto-completion of API endpoints and inferred data from backend to frontend. tRPC works the same way in React Native and can be adopted incrementally. The example showcases backend communication with a database using queries and validators, with types inferred to the frontend and data retrieval done using Prisma ORM.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.