Тёмный

How Did I Not Know This TypeScript Trick Earlier??! 

Josh tried coding
Подписаться 131 тыс.
Просмотров 200 тыс.
50% 1

This TypeScript trick to conditionally include types is so useful, especially for React props. I've asked myself how this is done many times before, and it's just really cool to learn something so simple yet useful.
-- links
Discord: / discord
My GitHub: github.com/joschan21

Наука

Опубликовано:

 

4 июл 2023

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 481   
@WebDevSimplified
@WebDevSimplified 10 месяцев назад
This is a trick I have been using for a while and really love it. One thing to note about this is that normal TS utility types like Omit and Pick will not work with Unions so you need to write your own version of these utils that look like this. export type UnionOmit = T extends unknown ? Omit : never
@satindar31
@satindar31 10 месяцев назад
Thanks
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Interesting. Thanks for sharing man!
@viktormalmedal265
@viktormalmedal265 10 месяцев назад
Small tip, the type string | number | symbol is equal to the global type PropertyKey :) type Foo = PropertyKey; // ^? string | number | symbol
@nabinsaud4688
@nabinsaud4688 10 месяцев назад
Why doesn't it create a table in my local db it pushes and migrate but does not create a table why tried many solutions not working
@amixengineer
@amixengineer 10 месяцев назад
Great trick, I used to get the same result with function overloading but that require a lot of type checking.
@mattpocockuk
@mattpocockuk 10 месяцев назад
Great video! Here's the correct terminology to help people google this stuff: Props is a discriminated union. 'gender' is the discriminator. The if statements you use to check members of the union aren't type guards, that's something slightly different. You're doing 'narrowing'. Love seeing these tips out in the wild!
@vikingthedude
@vikingthedude 10 месяцев назад
I thought this was a parody account at first
@tif7305
@tif7305 10 месяцев назад
Thank you for the terminology, I feel missing that makes it impossible to learn and compare techniques, so it is very much appreciated.
@gubatenkov
@gubatenkov 10 месяцев назад
so what is type guards then?
@tif7305
@tif7305 10 месяцев назад
@@gubatenkov Type guard is when you test a variable on which type it is in an if statement to narrow it down. You can use e. g. instanceof, typeof or the in keyword for this. There is a great logrocket post about this, if you want to know more! just Google type guard typescript and you will find it
@mattpocockuk
@mattpocockuk 10 месяцев назад
@@gubatenkov Type guards are: const isString = (val: unknown): val is string => { return typeof val === 'string'; } You use the 'is' syntax to annotate a function to be a 'type guard', or 'type predicate'.
@vikingthedude
@vikingthedude 10 месяцев назад
For those curious, these are called tagged unions or discriminated unions. The typescript docs mentions them. They are common in functional languages and also in most newer languages like Rust. They are from a category of types called "sum types". What we're used to in OOP languages are usually "product types"
@marikselazemaj3428
@marikselazemaj3428 10 месяцев назад
well said 👍
@tuananhdo1870
@tuananhdo1870 6 месяцев назад
I learned this from elm
@bano377
@bano377 10 месяцев назад
I think that it's better to write code more explicit interface Person { name: string; } interface Male extends Person { gender: "male", salary: number; } interface Female extends Person { gender: "female"; weight: number; } type Props = Male | Female;
@ensi.creator
@ensi.creator 10 месяцев назад
oh, that looks so much better
@lasindunuwanga5292
@lasindunuwanga5292 10 месяцев назад
composition vs inhertitance?
@bernardcrnkovic3769
@bernardcrnkovic3769 10 месяцев назад
@@lasindunuwanga5292 there is no inheritance because it is an interface. interfaces cant inherit as they dont have behavior
@lasindunuwanga5292
@lasindunuwanga5292 10 месяцев назад
@@bernardcrnkovic3769 so you are telling me it is okay to build an heirachy of interfaces?
@rnz2363
@rnz2363 10 месяцев назад
There is no need for using interfaces. Interfaces are much more extensive in terms of functionality than regular type aliases. Using the extends keyword is not more "explicit". Intersection types (with the & operator) have pretty much the same semantics. Interfaces should be used when describing abstract types (for example, when doing polymorphism). You should not use an interface if you're not planning on using the implements keyword on other concrete types. Interfaces are not as flexible as type aliases, because they only allow object types. Also, interfaces can be overwritten in other places of the code, just by having another definition of it, or even multiple other definitions. Type aliases are much more simple and generic, they are just a way to give some type a name in order to re-use it or export it. I would prefer something like that: type Person = { name: string } type Male = Person & { gender: 'male' salary: number } type Female = Person & { gender: 'male' weight: number } type Props = Male | Female
@bryson2662
@bryson2662 10 месяцев назад
I believe these are called discriminated unions
@letfoobar
@letfoobar 10 месяцев назад
Yes, those are discriminated unions
@markzuckerbread1865
@markzuckerbread1865 10 месяцев назад
I'm surprised so many people are finding out about this so late
@RonaldTetsuoMiura
@RonaldTetsuoMiura 10 месяцев назад
Males are required to declare their salary, while females are required to declare their weight? Indeed, a very discriminatory union 😂
@specy_
@specy_ 10 месяцев назад
@@markzuckerbread1865 i feel like disciminated unions are 90% of what makes typescript awesome, everyone should know it
@elfelipe1996
@elfelipe1996 10 месяцев назад
It's so weird that the newer typescript docs removed the docs for discriminated unions. You can only find it in the old docs
@Volbeast22
@Volbeast22 9 месяцев назад
This was awesome man! Great explanation, been wondering how to get those conditional types to be so easy and you just nailed it!
@muhammedmaher6704
@muhammedmaher6704 10 месяцев назад
I've been looking for this specific trick for a very long time to no avail! thank you man! 🔥
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Same, really glad it's this easy
@martinharyanto8262
@martinharyanto8262 10 месяцев назад
Please do more videos like this. This is very beautiful and and very nice. This can makes me refactor whole bunch of my component props type kudos Josh ! Great content !
@MisouSup
@MisouSup 10 месяцев назад
I just found your channel and I am really liking it. Good quality stuff :D
@uixmat
@uixmat 9 месяцев назад
I was trying to figure out how to do this recently with no luck, so glad you uploaded this mate!
@jaredbecker3152
@jaredbecker3152 4 месяца назад
Saw this video when it first came out and thought it was really cool but never had a need for it until today so now I'm back to refresh my memory. Thanks Josh for this awesome little trick
@aminerhouma
@aminerhouma 10 месяцев назад
I really enjoyed learning that awesome trick you shared, especially with the helpful examples you provided. Your thoughts were also well-organized, which made it easy to follow along. Thank you!
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Cheers man
@poizonncs8264
@poizonncs8264 10 месяцев назад
Love the way you explained, Loud & Sharp. Subscribed
@Ivcota
@Ivcota 10 месяцев назад
Something similar happens when using the Zod parser. If you look the generic output type, you’ll notice how the isSuccessful being true is constraint to the output that contains the data while isSuccussful being false is constraint to the output that produces and error. The parsing logic os handled within the library but can be a good source of inspiration for these types of unions. Great video 🎉
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Mhmm that's interesting too. Thanks for sharing man, cheers
@AsToNlele
@AsToNlele 10 месяцев назад
Loved the examples, thank you Josh!
@BlurryBit
@BlurryBit 10 месяцев назад
Life saving!!! I was looking for this for a long time. Thanks for the tip man! :)
@jacob_dmn
@jacob_dmn 8 месяцев назад
Really needed this since a long time!!
@daromacs
@daromacs 10 месяцев назад
amazing Josh, thanks for sharing and to the point, also noticing the real use cases!
@jakeave
@jakeave 9 месяцев назад
This is exactly what I've been looking for. I've kind of just dealt with the possibly undefined properties. Great explaination!
@jenewland1999
@jenewland1999 10 месяцев назад
Great vid Josh 👍🏻 Always amazing when you learn these sorts of tricks in TS. One I learnt yesterday that's pretty cool is if you want intellisense for a string type that has set responses as well as the ability to pass any string you can do: type Gender = "male" | "female" | "prefer not to say" | (string & {}); now when you bring up autocomplete rather than getting nothing you'll get male, female, and prefer not to say listed in the dropdown. (Credit to Matt Pocock for this one)
@Osirisdigitalagency
@Osirisdigitalagency 10 месяцев назад
Can you kindly provide the link to this video?
@jenewland1999
@jenewland1999 10 месяцев назад
@@Osirisdigitalagency Sure! ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-8HoOxOd86M4.html
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
I heard about that too! Very cool concept
@christopherreif3624
@christopherreif3624 9 месяцев назад
I think this is super useful, and I too with I would have known this sooner. Thanks for posting!
@CrankyBarbar1an
@CrankyBarbar1an 10 месяцев назад
THIS IS HONESTLY SO COOL. I was actually in a similar position, where I wanted conditional typesafety, but I legit couldn't find exactly what I was looking for. And this video was just that. I honestly loved it, THANK YOU SO MUCH!!
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
You're welcome dude yeah I was really happy when I discovered this too
@AnindoSarker
@AnindoSarker 10 месяцев назад
I randomly found out your channel and I'm happy. Quality content as always
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Thank you mean. That means a lot.
@eof_lemongrab
@eof_lemongrab 10 месяцев назад
Keep up the great work Josh!
@donaldsilveira
@donaldsilveira 10 месяцев назад
Thank you so much for this video, you just shipped it when I was looking how to do exactly it! 😂😂
@ziadxcode
@ziadxcode 7 месяцев назад
bro I have been searching for a way to make conditional types, thank you!
@HorizonHuntxr
@HorizonHuntxr 10 месяцев назад
This is awesome! I ran into rhis problem recently and ended up just allowing the user to pass all the props without discrimination but knowing this now is a huge help! The only downside i see to this is that you will keep getting typerrors until you fulfill all the requirements by passing all the necessary props but that's a small trade off for something so powerful
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
You could still make them optional! There really are some great benefits to this
@psyferinc.3573
@psyferinc.3573 10 месяцев назад
im glad your getting into typescript
@yatinm9250
@yatinm9250 10 месяцев назад
Great video. I needed this quite recently. Thanks.
@samueldonsmog6006
@samueldonsmog6006 8 месяцев назад
This is very helpful. Thanks
@maomorin
@maomorin 10 месяцев назад
DAAAAAAAMN!!! I have searched for this ages!!! I tried to make it with conditionals but this way is just what I needed :D thanks for share!
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
awesome dude
@tarakganesh1472
@tarakganesh1472 10 месяцев назад
Thanks man!! Have been looking for a solution for this scenario.
@daniloochoahidalgo9783
@daniloochoahidalgo9783 10 месяцев назад
Just discovered this about the same time as you, it seems to be. Good video!
@XON532
@XON532 9 месяцев назад
TypeScript is going to be yummy han anytime. Appreciate sharing the valuable tip.
@santicanabalramos667
@santicanabalramos667 10 месяцев назад
Great video! By the way, in the conditional statement, because there are only 2 options for the gender property, you can turn the else if into just an else. Conditional types are one of the most powerful features in typescript. I love your videos, keep going 🙂
@CyberMew
@CyberMew 10 месяцев назад
What do you mean? Do you have a small example of it?
@xReDxTuRtLeZx
@xReDxTuRtLeZx 10 месяцев назад
ahhhh i recently did something similar but used if statements. this is so much cleaner and makes more sense. def a good tip
@Alluriah
@Alluriah 9 месяцев назад
sooo cool and intuitive!
@OleksandrBorysenko333
@OleksandrBorysenko333 10 месяцев назад
Nice trick! Thanks for sharing.
@emee__
@emee__ 10 месяцев назад
Bro you just saved me right now, I was searching for this 👍👍👍
@Alan-tx6et
@Alan-tx6et 10 месяцев назад
that's something that i needed really much thanks
@developerpranav
@developerpranav 10 месяцев назад
0:16 I like how you're using components from other file without even importing them. That's more magical to me
@parlor3115
@parlor3115 10 месяцев назад
Unless he's using a plugin that manages imports behind the scene, I'd say this is because of a bug in VS Code that suppresses import errors when the target isn't exported. TypeScript won't compile it in this case, though.
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
yeah NO idea why this is, my vscode just started doing it. based
@mhmdalharbi2370
@mhmdalharbi2370 9 месяцев назад
Because both child and parent are not modules, so Typescript treat them both as globals
@richardjamesbunker
@richardjamesbunker 10 месяцев назад
Awesome video. Very clear and helpful. Thank you!
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Cheers man
@suryak3040
@suryak3040 8 месяцев назад
Nice explanation man 👍.
@harmmeijer6582
@harmmeijer6582 9 месяцев назад
Nice video, thank you. You could add exhaustive switch on union types when using it: export function matchGuard(_: never): never { throw new Error('Unreachable code in match guard') } In code using your person if(props.gender==='male'){ return '' } if(props.gender==='female'){ return '' } matchGuard(props) If you add another gender later the line "matchGuard(props)" will give you a compile error.
@krishnayallapanthula
@krishnayallapanthula 6 месяцев назад
Great explanation. Thank you.
@adammilner4512
@adammilner4512 10 месяцев назад
Bro huge thanks to you , i comment really rare, but the information you shared in this video helped me so much
@bigjamar
@bigjamar 9 месяцев назад
Muchísimas gracias, excelente!!
@torickjdavis
@torickjdavis 10 месяцев назад
This is an extremely useful feature in TypeScript. Often the usage of a union type (separated by a pipe "|") that can be distinguished by a literal value is known as a "discriminated union". Researching that is extremely helpful for finding use cases.
@devinjameson352
@devinjameson352 6 месяцев назад
Neat! I might suggest starting with something super explicit like this introducing additional complexity to the type system as needed. type Props = { person: Person } type Person = Male | Female type Male = { kind: "Male" name: string salary: number } type Female = { kind: "Female" name: string weight: number }
@Saturn2888
@Saturn2888 10 месяцев назад
I literally just recommended this method at work today. Since I use only types and not interfaces, I had to come up with creative ways to do conditional types.
@PatrickMeppe
@PatrickMeppe 7 месяцев назад
I finally had a use case today where I applied this approach. 🙂
@ahsanimam5243
@ahsanimam5243 10 месяцев назад
Very well done Sir! Thank you
@rembautimes8808
@rembautimes8808 5 месяцев назад
Thanks for sharing. Useful tool in reducing errors and leveraging intelisense.
@baka_baca
@baka_baca 10 месяцев назад
This was clearly explained and feels useful 🎉
@mluevanos
@mluevanos 10 месяцев назад
When I use Typescript and React, I like to create an interface and extend the HTML attributes onto it like so: interface MyComponent extends React.HTMLAttributes { // Extends props } And that will add className, name, onClick, and all other attributes related to an HTML DIV Element.
@runonce
@runonce 10 месяцев назад
Do you spread the rest of the props? Or do you destructure each prop of the native element?
@gabrielkyomen4782
@gabrielkyomen4782 10 месяцев назад
Wow. I was trying to google this for weeks and didn't quite got the correct terminology. Thx for sharing!
@KerimWillem
@KerimWillem 5 месяцев назад
Very useful, thank you!
@kevinc4736
@kevinc4736 10 месяцев назад
Thank you sir! Gonna be able to use way less question marks now
@mateja176
@mateja176 10 месяцев назад
In the case of multiple branches, you could use “satisfies” to ensure that the keys and types do not get mixed up. For instance “satisfies { gender: string }”
@ExtraterrestrialCatgirl
@ExtraterrestrialCatgirl 10 месяцев назад
hey that sounds interesting, could you explain it a little bit more? :) that sounds interesting but I can't really figure out what exactly to do with the "satisfies" keyword here
@yousafsabir7
@yousafsabir7 10 месяцев назад
​@@ExtraterrestrialCatgirl yeah, maybe a code snippet would do
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
the satisfies keyword is super interesting too. Gonna look more into this typescript stuff, it's actually cooler than I thought
@MrMoonCraft
@MrMoonCraft 10 месяцев назад
@Joshtriedcoding1 love the realization 5 hours later 😂😂
@einargs
@einargs 10 месяцев назад
Typescript has some truly awesome tools for building types. I cannot recommend reading the full docs enough.
@mporcar
@mporcar 9 месяцев назад
awesome! which extension are you using for Intellisense?
@xingfucoder2627
@xingfucoder2627 6 месяцев назад
Great content! could you make a TypeScript series about all those advanced concepts? Would be great. Or maybe a course will be appreciated.
@Kay_Drechsler
@Kay_Drechsler 10 месяцев назад
Awesome trick and well explained! Could you maybe elaborate on the VSCode keyboard shortcuts you are using to destructure types, to see necessary types and the like?
@dominikalkhovik8537
@dominikalkhovik8537 10 месяцев назад
Cool video, I was wondering what shortcut/ extension was used when clicking on the type to have it added to the deconstructed props.
@justin_t
@justin_t 6 месяцев назад
very neat trick! please show more videos!
@petrblinkov508
@petrblinkov508 9 месяцев назад
You can setup ApiResponse or ApiResponse for Error response and allow to use it as ErrorApiResponse in any Api not only for number
@Jrrs2007
@Jrrs2007 10 месяцев назад
HELL YES!! Nice video!!
@majidghafoorzade9906
@majidghafoorzade9906 10 месяцев назад
Very useful video. thanks 👌
@mohamedzaheen3246
@mohamedzaheen3246 10 месяцев назад
Great job josh
@ameer6168
@ameer6168 9 месяцев назад
0:34 bro is menace to the society
@MrPeepa
@MrPeepa 10 месяцев назад
What are you using to just click on the type definition and complete the Props in 1:22 ?? Great video by the way, didn't really know this existed in typescript, although coming from OOP I was really looking for something like this.
@Black_void375
@Black_void375 9 месяцев назад
nice video man
@MarcioJustoDev
@MarcioJustoDev 5 месяцев назад
Hi Josh. Excellent explanation. Is it possible to do this using some logic in a inner function instead of status: 'success'? Something like status: (value: T) => check something
@kingsleykelechionwuchekwa7508
@kingsleykelechionwuchekwa7508 10 месяцев назад
Ohh that's cool😮. Thanks for the trick
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
youre welcome dude
@joonesmusic
@joonesmusic 7 месяцев назад
Awesome, thank you!
@0xpatrakar
@0xpatrakar 10 месяцев назад
This guys points out some really obvious things that I have been using for a while but looking at comments apart from 2 or 3 comments everyone finds these tips useful. It leaves me baffled.
@Matt23488
@Matt23488 10 месяцев назад
TypeScript is an incredibly powerful language for describing your APIs with very specific types. It's one of my favorite languages because of this.
@voidtraveller01
@voidtraveller01 8 месяцев назад
Thanks for the trick. No more undefined checking. But I wonder can we do this in Prisma schema?
@petarkolev6928
@petarkolev6928 10 месяцев назад
Wow, you got an insta sub from me, man, super video!
@misterl8129
@misterl8129 10 месяцев назад
this is pretty good actually, thanks!
@misterl8129
@misterl8129 4 месяца назад
this is in the documentation?¡ :o
@axiinyaa
@axiinyaa 10 месяцев назад
i don't even program with typescript but i'm so interested in these kind of things
@ThanHtutZaw3
@ThanHtutZaw3 8 месяцев назад
so I can use this for passing same props with different types ? example passing files that can be files type and custom file type . Currently using 'as' when passing props and using props.
@shinshinremix6324
@shinshinremix6324 10 месяцев назад
Nice! Thank you very much
@jdmaldonado06
@jdmaldonado06 8 месяцев назад
Thanks so Much!
@joshtriedcoding
@joshtriedcoding 8 месяцев назад
Youre welcome!
@alexbritto634
@alexbritto634 7 месяцев назад
Excelent! How can I do this using interface instead type?
@lazarobl
@lazarobl 9 месяцев назад
This is such a based tutorial, I love it 😂
@DennisPeters39
@DennisPeters39 10 месяцев назад
Junge, heute noch das Problem gehabt und zufällig haust du nen Video raus. Danke dir 👍
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
You're welcome dude, nice to hear
@ryangamv8
@ryangamv8 10 месяцев назад
I just recently learnt about the TS "in" keyword. It's also really useful for union types where you don't have a discriminator like the "gender" field in this example. You should do a vid on that too!
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
Gonna look into it, thanks for the suggestion dude
@DubiousNachos
@DubiousNachos 10 месяцев назад
That's not exclusive to TypeScript. JavaScript has it, too
@ryangamv8
@ryangamv8 10 месяцев назад
@@DubiousNachos huh yeah TIL. It does really help specifically in TS cos of what I said above. That is you can't even do something like 'if (person.salary === undefined)...' in the above case but you can use the 'in' keyword
@igboanugwocollins4452
@igboanugwocollins4452 3 месяца назад
Thank you for this
@sire_ns
@sire_ns 10 месяцев назад
Need more such videos
@damiantriebl1747
@damiantriebl1747 9 месяцев назад
good tip!, this tips are super usefull!!
@John-Dennehy
@John-Dennehy 10 месяцев назад
I've previously achieved this with Never type, but not seen this approach before. Interesting
@KevinVandyTech
@KevinVandyTech 10 месяцев назад
Just 4 days ago, I figured out something very similar for my OSS project. I figured out how to make an xor type that is like this, but will require props from the 2 different set of types to be mutually exclusive. Just 1 set of props or the other, not all.
@dinoDonga
@dinoDonga 10 месяцев назад
Care to share?
@Ultrajuiced
@Ultrajuiced 10 месяцев назад
Something like { a: number; b?: never; } | { a?: never; b: string; } ?
@KevinVandyTech
@KevinVandyTech 10 месяцев назад
@@Ultrajuiced I've tried responding but my youtube comments are always deleted. oh well
@bollo_omar
@bollo_omar 10 месяцев назад
This is wonderful
@buddy.abc123
@buddy.abc123 10 месяцев назад
Let me go refactor my code, this is exactly what I need earlier. Thank you Josh
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
You're welcome champ
@gautamjh
@gautamjh 3 месяца назад
Great video!
@apanchuk
@apanchuk 9 месяцев назад
1:22 how did you do this, click on property name in the interface and got it desctructured in props in the component?
@THE16THPHANTOM
@THE16THPHANTOM 9 месяцев назад
so that code is basically doing inheritance? a fancy way of doing inheritance.
@loO5r
@loO5r 4 месяца назад
Really cool trick! Downsides I see compared to the "classical" way with Interface Male extends Person {...} is: - it is harder to read for other team members (React novices or even non React developers) - it works only binary. As soon as you have more than two options, you need to refactor the code anyway (and no, I didn't meant to start any gender discussion rn)
@rajfekar1514
@rajfekar1514 10 месяцев назад
Great 😃👍 I learn something new in typescript.
@joshtriedcoding
@joshtriedcoding 10 месяцев назад
nice!
Далее
7 Awesome TypeScript Types You Should Know
8:57
Просмотров 74 тыс.
Did Netflix Just Drop a Banger?
10:42
Просмотров 28 тыс.
Generics: The most intimidating TypeScript feature
18:19
I Got a Job at Upstash...
3:32
Просмотров 26 тыс.
If I Started Learning TypeScript, I'd Do This
6:12
Просмотров 34 тыс.
Common Mistakes and Advanced Typescript Techniques
10:49
I Can't Believe I Didn't Know these Typescript Hacks
10:49
I Made This Open-Source Project
7:22
Просмотров 63 тыс.
This TypeScript Trick Blew my Mind
6:17
Просмотров 36 тыс.
4 ways to use the TypeScript infer keyword
10:08
Просмотров 12 тыс.
Вы поможете украсть ваш iPhone
0:56
Wow AirPods
0:17
Просмотров 642 тыс.