The KEY to unions and intersections in TypeScript

  Рет қаралды 9,705

Andrew Burgess

Andrew Burgess

Күн бұрын

Unions and Intersections are core features of TypeScript, but they can be rather confusing when you first start using them. These quick tips will make everything much clearer!
Learn More
ivov.dev/notes/typescript-and...
• TypeScript Berlin Meet...
effectivetypescript.com/2021/...
shaky.sh

Пікірлер: 30
@lukejagodzinski
@lukejagodzinski Жыл бұрын
Yep that was one of the most confusing things when learning TypeScript. It gets even worse when you start working with it. Consider this example: type HasName = { name: string }; type HasAge = { age: number }; type HasNameOrAge = HasName | HasAge; (user: HasNameOrAge) => { // user.
@andrew-burgess
@andrew-burgess Жыл бұрын
Great point! Now wish I’d remembered to put this in the video. I’ll just ping your comment instead 👍
@connorallen162
@connorallen162 Жыл бұрын
Somehow I missed this commend and commented the same thing (though slightly less thoroughly). I feel like it's important to communicate the limitations and inconsistencies, because it gets super frustrating to feel like this unexpected behavior is user error when typescript is really just an imperfect system with some rough edges.
@pawekoaczynski4505
@pawekoaczynski4505 Жыл бұрын
Yup, this exact thing caused me hours of research. And when I finally submitted the PR, the other developer said to me "that doesn't seem very safe, because you're using a string". I had to show him that the autocomplete and type safety indeed works as expected. TypeScript has some warts
@zorzysty
@zorzysty Жыл бұрын
@lukejagodzinski @andrew-burgess As of TS version 4.9, the following code: if ("name" in user && "age" in user) { console.log(user.age) console.log(user.name) } is perfectly fine, it won't throw any errors, and you will get autocompletion for both age and name.
@lukejagodzinski
@lukejagodzinski Жыл бұрын
@@zorzysty it's not. The inferred type will not be `HasName | HasAge` but instead it will be `HasName & Record`. It looses info that `age` is a number.
@peterkohout7901
@peterkohout7901 4 ай бұрын
Its like turning on a bright light in a very dark room. Love your ability to clearly express confusing and difficult concepts. Thank you for your generosity In making this available.
@zavarka2
@zavarka2 Жыл бұрын
I love this video. For the first time in so many years of using TypeScript, I understand why these types are called intersections and unions.
@vrojak7636
@vrojak7636 Жыл бұрын
Those 4 minutes were more valuable than 30 min of browsing the web in confusion
@wontcreep
@wontcreep Жыл бұрын
actually helpful and easily comprehensible :)
@mmmike3426
@mmmike3426 Жыл бұрын
Oh damn, this completely changed my perspective - and made the naming convention of union and intersection types make sense.
@andrew-burgess
@andrew-burgess Жыл бұрын
Thanks so much! This is exactly what I was hoping for 😀
@xtremehackerzpro9511
@xtremehackerzpro9511 7 ай бұрын
Wow what a nice explanation :)
@BrunoReisVideo
@BrunoReisVideo Жыл бұрын
could you maybe talk about your dot-files folder in a future video? i’m starting to accumulate terminal apps and am having trouble organizing them and understanding .bash_profile and all that kind of stuff
@andrew-burgess
@andrew-burgess Жыл бұрын
Great suggestion, thanks! Definitely adding that to the list.
@muhammadfaruq1782
@muhammadfaruq1782 Жыл бұрын
I was surprised how understandable tNice tutorials tutorial is, thanks!
@user-uf1ne1ic6i
@user-uf1ne1ic6i 5 ай бұрын
what about this: type oneAndAny = 1 & any; // the result is any; The intersection of value that can be assigned to type 1 and values that can be assigned to type any is still 1 , right ? Shouldn't the result be 1 ?
@user-uf1ne1ic6i
@user-uf1ne1ic6i 5 ай бұрын
i think Intersection types is just represent creating a new type that simultaneously satisfies all intersected types.
@Adamskyization
@Adamskyization 11 ай бұрын
So Basiaclly,Given func(A), func(B). The '|' operator is a logical OR. so you can do func(A), func(B), func(A,B) and the intersection operator '&' is a logical AND. so you can do func(A, B) only. Seems that "intersection" is not the right name for the operator '&' in typescript, as it contridcts the term of Intersection in computer science. Intersection of func(A) and func(B) will be the empty group. I asked chatGPT to come up with some alternative names Combination Type: The "&" operator combines multiple types to create a new type, much like combining elements from different sets. "Combination Type" accurately describes the operation without conflicting with the traditional definition of intersection. Merged Type: The "&" operator merges the properties and methods from different types into a single type. This reflects the act of merging or bringing together multiple entities into one cohesive entity. Composite Type: The "&" operator creates a composite type by assembling various types into a unified structure. "Composite Type" implies the composition or integration of multiple types into a single entity. Collective Type: The "&" operator results in a collective type that includes all the features and attributes from the combined types. "Collective Type" signifies the idea of bringing together disparate elements into a comprehensive whole. Aggregated Type: The "&" operator aggregates properties and methods from multiple types into a consolidated type. "Aggregated Type" emphasizes the gathering or accumulation of various elements into a coherent type.
@IPKISS2006
@IPKISS2006 Жыл бұрын
same as mysql inner join and full join
@connorallen162
@connorallen162 Жыл бұрын
The fact that the union is not an exclusive-or doesn't seem well supported by typescript itself. See the example below: type Foo = { bar: string; test: boolean } | { wiggle: string }; const foo: Foo = { bar: "wiggle", wiggle: "wiggle", test: true }; if ("test" in foo) { foo.wiggle < ---------- This raises a typescript error } The "Union" behavior is valid when setting the value, but the that behavior isn't fully respected when reading the value. I feel like this is the kind of thing that makes typescript pretty annoying. Like, I want to believe typescript errors, but sometimes it doesn't follow it's own rules very well
@DirkLuijk
@DirkLuijk Жыл бұрын
What do you mean? Your code example totally makes sense to me. Just that you CAN assign a value from the intersection of the two types when it expects at least something from the union of the two types, doesn't mean you type narrowing is conclusive.
@edgarabgaryan8989
@edgarabgaryan8989 Жыл бұрын
here is another example of a non-intuitive TS type type A = { a: number; z: number; } type B = { b: number; z: number; } type C = keyof (A | B) // guess what this type is
@andrew-burgess
@andrew-burgess Жыл бұрын
Love this example! Thanks for sharing!
@gautierurso1824
@gautierurso1824 Жыл бұрын
damn, i failed ! i thought it was equivalent to type D = keyof(A) | keyof(B)
@usmanplayzmc4388
@usmanplayzmc4388 Жыл бұрын
Guys my GMS softs like a dead rat! How can i change it to the one that he has?
@lukejagodzinski
@lukejagodzinski Жыл бұрын
The linked article has actually an error in the Part 2: Type creation. The following example of union (also intersection) is incorrect. It's just the opposite of what is presented there. interface ICat { eat(): void; meow(): void; } interface IDog { eat(): void; bark(): void; } declare function Pet(): ICat | IDog {}; const pet = new Pet(); pet.eat(); // succeeds pet.meow(); // succeeds pet.bark(); // succeeds
@andrew-burgess
@andrew-burgess Жыл бұрын
Yeah, I’ve been meaning to email him about that. But otherwise, it’s a very helpful post.
@Luxcium
@Luxcium Жыл бұрын
I made to much direct compliment to our TypeScript SuperHero so now let me talk about him like he is not watching...Did anyone else realize how much the colours in the video always adapt to offer us with a slightly different mood from one video to the next...I love particularly how each time regardless of the colour of his shirt everything is in harmony... I must admit that I do appreciate those videos for many many different unrelated or interconnected reasons... 😅😅😅😅 I hope everyone is going to love as much as I do such that he would be too successful not to post at least twice a week 🫣😮‍💨😵 (yea I realize that it implies a ton of work and efforts to produce a good KZbin video 😅 I am probably selfish but since I know it will ultimately benefit the entire community across the boarders of many lands I am passing the remark)... 🎉🎉🎉🎉
Branded Types give you stronger input validation
9:22
Andrew Burgess
Рет қаралды 17 М.
Are your TypeScript Unions broken? | Advanced TypeScript
7:36
Andrew Burgess
Рет қаралды 7 М.
Double Stacked Pizza @Lionfield @ChefRush
00:33
albert_cancook
Рет қаралды 122 МЛН
ТЫ С ДРУГОМ В ДЕТСТВЕ😂#shorts
01:00
BATEK_OFFICIAL
Рет қаралды 6 МЛН
Typescript's Most Misunderstood Feature: Unions and Intersections
16:39
If Coding Were Natural
Рет қаралды 1,2 М.
How to use TypeScript Enums and why not to, maybe
12:43
Andrew Burgess
Рет қаралды 18 М.
Real-Time Operating System in 96 Lines of C | RIOS
10:04
Cheesed Up
Рет қаралды 49 М.
Interfaces vs Type Aliases: what's the difference?
10:20
Andrew Burgess
Рет қаралды 21 М.
Enums considered harmful
9:23
Matt Pocock
Рет қаралды 201 М.
Фишки TypeScript о которых ТЫ НЕ ЗНАЛ!
30:55
Building Fluent Interfaces in TypeScript
16:15
Andrew Burgess
Рет қаралды 14 М.
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 780 М.
I Cannot Believe TypeScript Recommends You Do This!
7:45
Web Dev Simplified
Рет қаралды 167 М.
Ускоряем ваш TV🚀
0:44
ARTEM_CHIBA
Рет қаралды 484 М.
Looks very comfortable. #leddisplay #ledscreen #ledwall #eagerled
0:19
LED Screen Factory-EagerLED
Рет қаралды 13 МЛН