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.

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

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

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.
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
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.

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.