TypeScript Survival Guide: Life-Saving Tips and Techniques

Rate this content

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.

7 min
21 Sep, 2023

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.

Available in Español

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.

3. Enums: Number, String, and Const

Short description:

For the next tip, Enums. Enums are one of the few structures in TypeScript that produce JS code. You can use number Enums, string Enums, or const Enums. Number Enums ensure matching either a number or its type, while string Enums are easier to read but require conversion for assignment. Const Enums replace calls with values in the final code, but don't standardize things and can't be accessed at runtime.

For the next tip, Enums. The big elephant in the room. While some don't like Enums, I'm particularly fond of them. But you need to know them. So, that is the tip. Know the Enums. So, let's start with the basic number Enum. Enums are one of the few structures in TypeScript that produces JS code. It looks hockey, but it makes sure that you will always be able to match either a number or its type. The problem is that you can use both and it kind of defeats the purpose of enumerating things, right? So, what we can do is that we can use the string Enums which are easier to read, but we cannot directly assign the value it contains to the variable that has its type. So, you need to convert, for example, a user input into a new value if you need to assign both. In my opinion, it's worth it because you standardize the code, however enum types can also be a very good substitute for this. And the final one is a const enum. It does not produce any output because it will replace its calls with its values in the transpiled.js, like magic. So, in this example, all the enum values will be replaced with their enums in the final code. It won't produce any output but also doesn't standardize the things, so there's still magic numbers popping up from nowhere. Also, const enums don't exist in runtime, so you cannot access their keys or values the same way you can do with others. So they're expanded into their underlying values and that's it.

4. Resource Disposal, Unknown Type, Case Conversion

Short description:

In PS 5.2, a new keyword called 'using' allows explicit control over resource disposal and memory cycle. Implementing 'unknown' protects data usage. Introducing case conversion utility type for snake case and camel case interfaces.

There's no coming back from them. For the next revolution, a new one, something that's pretty brand new. In PS 5.2, there's a new keyword, which is also coming to JS soon, that allows you to explicitly control resource disposal and memory cycle. It's the using keyword. It all starts with the symbol dispose or the async dispose that you put in an object class or anything that accepts a method like that. This method will do the work of disposing the resource and then you just need to declare a variable with async using or just using depending on your object, it's a sync object or not. And this is a very good life-saving tip because you can abstract a lot of the complexity from object lifecycle away from the usage of that object.

For one of our final tips I want to bring you the world of unknown and how we can actually save a lot of lives. In Klarna, we have a lot of places where we deal with legacy systems, especially those that were ported to TypeScript and all the places where people didn't know what to type, there isn't any there and that's very bad. Bad because we are literally disabling TypeScript for those types and we are not inferring anything. There is no types, we all know how bad any is in general, but there is a solution. This solution is unknown. We start implementing unknown and the catch is that everything can be assigned to unknown but unknown cannot be assigned to anything. So this way we protect the data where it's actually used.

And lastly, I wanted to introduce the case conversion utility type using uppercase, capitalized or lowercase. The context for this is that in Klarna we have a lot of other services using snake case and some other services that use camel case. Because of that, we needed to convert API calls and returns to the specific casing and this led to the creation of these duplicated interfaces where one was the snake case and the other one was the camel case. So you don't need to do this, obviously there is like an overcomplicated way of making it generic like I did here, but in this example what I'm creating is a type that takes a string, splits it from snake case using a recursive type and make it to camel case. And then we can use a mapping type to map all the keys from an object to camel case and now we don't need to duplicate our interfaces anymore. And that was it, basically. 10 tips in 10 minutes. So thanks a lot for being here and for listening to this, and if you do have any questions, please join me in my socials and in the websites down here.

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 Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.
TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
Top Content
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.

Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
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.
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
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.
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
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.
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. 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.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.