Understanding types as sets

Rate this content
Bookmark

The talk will introduce the concept of variance as in pertains to generic types. It will then show how this concept applies to TypeScript. While showing TypeScript example, I will try to help the audience form an intuition about variance. Finally we will look at what some of the design decisions in TypeScript mean for the soundness of the code we write, and what are some blind spots the compiler has.

FAQ

According to Tizian Cernikva Dragomir, types in JavaScript are viewed as a set of values that a variable can possess. Types define how data is represented in memory and how it behaves, including the operations that can be performed on the data.

In TypeScript, union and intersection operations on types are used to combine and intersect sets of values, respectively. Union creates a new type containing values from all combined types, while intersection results in a type that only includes values common to the intersected types.

The 'never' type in TypeScript represents the type of values that never occur. It is used in situations where a type operation results in a set with no valid values, effectively representing an empty set.

Yes, in TypeScript, objects can have more properties than those strictly defined by their type. TypeScript's structural typing system allows objects to be considered valid as long as they have at least the required set of properties, regardless of additional properties.

The 'object.keys' method in TypeScript returns an array of strings, which does not guarantee type safety when used to index the original object. This method's design intentionally prevents runtime errors that could occur from indexing with keys that are not present in the object.

In TypeScript, a type can have multiple base types due to its structural typing system. This means a subtype can be part of several super-types (base types), as long as it fits the structural requirements of these types.

In TypeScript, a union of object types creates a type that could represent any of the individual types, making property access unsafe unless the property is common across all types. An intersection, however, results in a type that combines properties from all intersected types, ensuring safe access to all included properties.

Titian-Cornel Cernicova-Dragomir
Titian-Cornel Cernicova-Dragomir
21 min
29 Apr, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk explores the concept of types and their relationship to variables in TypeScript, including primitive types, special types, and literal types. It also delves into unions and intersections of types, their canonical form, and their effect on sets of values. The Talk discusses object types, their defined members, and the behavior of access property checks. It highlights how unions and intersections can be used with objects and how they are reduced to a canonical form. The importance of base types in TypeScript and how they allow variables to hold instances of any subtype is also emphasized.

1. Introduction to Types and Values

Short description:

Hello, everyone. My name is Tizian Cernikva Dragomir. I work on the JavaScript infrastructure team at Bloomberg and contribute to the TypeScript compiler. In this talk, we will explore the concept of types and how they relate to variables. Types can be seen as a representation and behavior of data, but they can also be viewed as a set of values that a variable can possess. We will discuss primitive types in TypeScript, such as number, string, Boolean, as well as special types like never and unknown. Additionally, we will explore literal types and their application in set operations, such as unioning.

♪♪ Hello, everyone. My name is Tizian Cernikva Dragomir. Welcome to my talk, TypeSets Sets. A little bit about myself first. I work on the JavaScript infrastructure team at Bloomberg. I contribute to the TypeScript compiler. And if you've heard about me, you've probably heard about me from Stack Overflow, where I answer a lot of questions about TypeScript.

So I want to start off this talk with a very simple question. What is a type? It's often very simple questions that can allow us to gain new insight. When we first start to learn programming, we will look at types as something that we associate with a variable. We will probably also learn that this data type has something to do with the way that data is represented in memory. So for example, integers are represented on 32 bits, strings are a sequence of characters, objects are also represented in memory in a particular way. So we come out with the impression that a type is representation and behavior, behavior meaning the operators that can manipulate those values. But there is also a different way to look at a type, namely, as a value space.

So a type is a set of values that the variable can possess. And let's look at some of the primitive types in TypeScript and how those relate to this definition. For example, the type number is the set of all floating point values. The type string is the set of all text values. The type Boolean is the set of values true and false. There are also some special types in TypeScript, namely the never type, which, since it has no possible values that can exist at runtime, it represents the empty set. And the unknown type, which represents the set of all possible values in Javascript. So let's take this new way of looking at types and try to apply them to some types we probably already know. Let's try to create a type that describes a set with a single value. In TypeScript, such types are denoted by their associated values. So we can define a type that is the value Yes, 1, or True. And once we've defined these types, if we associate them with a variable, then that variable can only contain the value that is part of that set. So, for example, if we associate Yes with a variable, it can only hold Yes. It can never hold the value No or any other string value. Now, literal types are not particularly useful until we associate them with one of the basic operations that we can do on sets, namely unioning. When we create a union of two existing sets, we create a new set that contains the values of both of the original sets.

2. Union and Intersection of Types

Short description:

In Typescript, creating a union from multiple types allows for a new type that can have values from all the constituent types. The intersection of string and number types results in the empty set represented by the never type. Intersecting boolean-like with the string set yields the values Yes and No. TypeScript reduces types containing Union and Intersection operators to a canonical form, expressing them as a Union of intersections.

So, similarly, in Typescript, if we create a union from our three existing types, using the pipe operator, what will happen is that we create a new type that can have values from all three of these constituent types. So our new type can contain the values 1, True, and Yes, but it can't, for example, contain the value No.

Let's take a look at the other operation we can do on sets, namely intersection. Now, let's say we have two primitive types, namely string and number, and we want to see what the intersection of these two types would be. Well, what value at runtime is both a string and a number? The answer is that there is no such value. So these two sets are actually completely disjointed. So their intersection would be the empty set. And TypeScript represents the empty set through the never type. So this intersection would be Never.

But let's see if we can do something more useful with intersections. Let's say we have this union of literal types. And we would like to extract the string components of this union. How could we use intersections in this case? Well, if we were to intersect boolean-like with the string set, what values would be in this intersection? And the answer is just the values Yes and No. The other values wouldn't fill the criteria, right? 0 and 1 are not string types, neither is True and False. So if we create this type, TypeScript will agree with us and say, Yes, just strings is Yes and No. And similarly, we could extract numbers if we intersect with number. We could also extract the booleans if we intersect with boolean.

Now something very interesting happens here since boolean just contains True and False. Since the result of this intersection would just be True and False, what just boolean ends up being is, of course, just the boolean type because boolean is just the Union of the literals True and False. But let's take a look at why exactly this works. Why does TypeScript perform this reduction? Well, TypeScript will try to bring all types that contain Union and Intersection operators to a canonical form. Namely, it will try to express our type as a Union of intersections, and it will apply distributivity to arrive at this result. So, for example, if we take the just strings type we created before, what TypeScript will first do, it will expand out that Union. And it will then try to take the intersection and move it closer to each one of the Union constituents. So we will get this type. What happens now? Well, if we take the intersection of String, which contains all string values, and of the type Yes, which is the set of just the Yes value. What do we get? Well, the answer is we just get the Yes value. We get Yes out of this. So we don't have to keep all of this around, we can just leave the Yes type alone. What about No? Well, the situation is similar.

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

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
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
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.
Stop Writing Your Routes
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.
Making Magic: Building a TypeScript-First Framework
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.
The Eternal Sunshine of the Zero Build Pipeline
React Finland 2021React Finland 2021
36 min
The Eternal Sunshine of the Zero Build Pipeline
For many years, we have migrated all our devtools to Node.js for the sake of simplicity: a common language (JS/TS), a large ecosystem (NPM), and a powerful engine. In the meantime, we moved a lot of computation tasks to the client-side thanks to PWA and JavaScript Hegemony.
So we made Webapps for years, developing with awesome reactive frameworks and bundling a lot of dependencies. We progressively moved from our simplicity to complex apps toolchains. We've become the new Java-like ecosystem. It sucks.
It's 2021, we've got a lot of new technologies to sustain our Users eXperience. It's time to have a break and rethink our tools rather than going faster and faster in the same direction. It's time to redesign the Developer eXperience. It's time for a bundle-free dev environment. It's time to embrace a new frontend building philosophy, still with our lovely JavaScript.
Introducing Snowpack, Vite, Astro, and other Bare Modules tools concepts!
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
Type-checking a TypeScript codebase can be slow, especially for monorepos containing lots of projects that each need to use the type checker to generate type declaration files. In this talk, we introduce — for the very first time — a new TypeScript feature we are working on called “Isolated Declarations” that allows DTS files to be generated without using the type checker at all! This opens the door to faster declaration generation in TypeScript itself, as well as in external tools written in other languages such as ESBuild and swc. You'll see how to use this new option, and maybe (just maybe) you’ll be convinced about the benefits of explicit return types! Most importantly, we will show how Isolated Declarations enables parallel builds to spread work across your CPU cores to significantly improve the build speed of your TypeScript projects.

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.
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.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
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.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
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.
Advanced TypeScript types for fun and reliability
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
Maurice de Beijer
Maurice de Beijer
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
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
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.