Woah! Can TypeScript Do That?

Rate this content
Bookmark

These days, TypeScript is an industry default as it provides amazing DX with autocomplete, confident code refactoring and much more. But most developers only scratch the surface and doesn't use Typescript to its fullest potential.


This talk would dive into the powerful and advance concepts of TypeScript like generics, conditional types, type guard, utility types for type transformations and much more using real world examples to better understand these concepts.

This talk has been presented at JSNation 2023, check out the latest edition of this JavaScript Conference.

FAQ

Typeguards in TypeScript are used to ensure that a variable belongs to a specific type within a conditional block. By using typeguards, TypeScript can recognize the type of a variable once a check passes, allowing you to use all associated methods and properties of that type.

In TypeScript, generics can make a React component more reusable by allowing you to define flexible and dynamic types for props and states. This enables the component to handle various data types and structures, enhancing its adaptability and reusability across different contexts.

The 'keyof' keyword in TypeScript returns all the keys of an object as a union type. For example, if you have an object with keys 'name', 'age', and 'email', using keyof on this object would return 'name' | 'age' | 'email'. It is useful for referencing the property names of an object type.

Utility types in TypeScript, such as Partial and Readonly, modify the properties of an object. Partial makes all properties of an object type optional, useful for updates that might only affect some properties. Readonly makes all properties of an object type immutable, meaning they cannot be reassigned once defined.

Custom utility types in TypeScript allow developers to create specialized type transformations that can enforce additional type constraints or behaviors, providing a powerful way to handle various data transformations and validations within the type system.

String literal types in TypeScript allow you to specify exact string values that a type can hold. This is particularly useful for creating more precise type definitions, such as for configuration values, property keys, or specific command types that a function might accept.

Nikhil Kumaran S
Nikhil Kumaran S
41 min
05 Jun, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today's talk covers advanced concepts of TypeScript including type guards, generics, utility types, and conditional types. These concepts enhance the developer experience and improve code quality by ensuring type safety and reducing errors. The talk also explores the use of generics to make components more generic and reusable. Additionally, it discusses the power of custom utility types and the infer keyword in creating flexible and precise type definitions. TypeScript's string templates are highlighted as a tool for enforcing restrictions on values like margins in CSS. Overall, the talk provides valuable insights into leveraging TypeScript's advanced features for more robust and maintainable software development.

1. Advanced Concepts of TypeScript

Short description:

Today's talk is about Advanced Concepts of TypeScript. Learn lesser-known TypeScript concepts to improve your developer experience. The first concept is typeguards. Typeguards help TypeScript determine the type of a variable. By using typeguards, you can ensure that TypeScript knows the variable's type and can use the appropriate methods. Another concept is assertions, which allow you to tell the compiler that a certain scenario won't happen again. By using assertions, you can prevent errors and ensure the expected behavior of your code.

Hi everyone, today's talk is about Advanced Concepts of TypeScript. Some lesser-known TypeScript concepts that you can learn and then use it in your day-to-day projects that you can dramatically improve your developer experience and you know, the usage of TypeScript itself, so let's continue.

Before we start, a little bit intro about myself, I am Nikhil, I am a Senior Front-end Developer at Syncradi. It's a data automation platform, and we do a lot of TypeScript stuff in there. So I also talk a lot on conferences and meetups, I also write blog posts and technical articles in all things JavaScript, TypeScript and React. So yeah, that's a bit of an intro about myself, and let's just jump into the talk.

So the first concept is typeguards. So let's see what it is. So let's say you have a function that takes in any argument type, and if it is of certain type, we do some kind of operation with it. For example, I'm here checking if it's a string, and if it's a string I'm using some string properties and accessing that. Otherwise, it's not a string, then we do it differently. So in this example, I have a string function that checks for the type of the variable and returns that it's a Boolean, it's a true or false. So with this, if you have it like this, then the typescript won't know if the variable is actually a string. So we have this check, it returns true or false, but there is no way typescript knows the variable is string or not. It just knows it's true or false and comes here and doesn't know about the type of the variable, right? So for that, what you can do is you can do some kind of typecode check here, so you can use the is keyword in typescript, and explicitly state that the variable is string as a return type here. So now what happens is, once this check passes, once it returns true, then typescript surely knows that this variable is of type string and it can use all the string methods that it has. So that's the beauty of this typeguard. So let's see an example in the code, actual example. So this is before adding the typeguard. So now if you see, this returns Boolean, this returns Boolean. And once you come here, now the variable is any and even after it returns true, the variable is any. So you don't get all the type checks, you know, at the compile time. So now after we add the typeguard, now here the variable is any, but once this check passes and comes here, now the variable is string. So which means we are telling the typescript that it is a string and you can use all the string methods that it has and it will be easy for us to do all the string operations within this true condition.

So now let's look at the assertions, so this is the way to tell the compiler that this scenario won't happen again. We are asserting it that it won't happen again. So in this function I'm testing if the variable is string or not. So if it's not a string, we throw an error. So if it's a string then there won't be any errors. So we call this function here with the variable passing into it and if it's not a string then there won't be any error.

2. Type Guards in TypeScript

Short description:

This part explains how type guards work in TypeScript. By using type guards, you can ensure that a variable is of a specific type and use the appropriate methods and properties. Type guards are particularly useful when you want to throw an error if a variable is not of the expected type. This concept is powerful and can improve the developer experience.

Then this console log will happen, so basically after this function execution is done, the variable would be a string and we are asserting that it is a string. So now what happens is, this return type is asserts and once we pass this function call, we know that the variable is a string then we get the variable as string and we can use all the string properties. So this is more powerful if you don't want to do a condition, Boolean condition and you want to throw an error in your example function there when it's not a string, you want to throw an error. So once the error is not thrown then we know for sure, it's a string and use all the string properties. So that's with a type guard.

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 2022React Advanced 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 2021React Advanced 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 2021React Advanced 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 2022React Advanced 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.