TypeScript Enums or Objects?
HTML-код
- Опубликовано: 24 авг 2024
- TypeScript's have Enums, which is a great language feature. However when you're writing libraries and exposing functions that try and require Enums it can make for a bad user experience.
Instead you should use regular ol' JavaScript objects - but super charged with TypeScript!
Have a watch and let me change your mind. :)
--
NEWSLETTER: tinyletter.com...
PATREON: / hswolff
TWITTER: / hswolff
SITE: hswolff.com/
You could have created a help type:
type ValueOf = T[keyof T];
type Colors = ValueOf
Useful, if this same functionality is being repeated multiple times. But it's really interesting how the typing system can be used as a tiny language of it's own to do amazing stuff like this.
I love this type of content, more TS videos please!
Woohoo! So glad you liked this!
The delivery sequence in this was incredible. I watched it, used it to fix an issue I've been toiling on for hours, then watched it again. Really good stuff
That’s so heartening to hear! Glad it helped!
Mind blown, I love where the channel is going lately, Deno, typescript and Rust ? Yes please !
All the type safety, all the time! :D
More TypeScript content pleeease, maybe with react/redux would be top
What questions do you have?
@@hswolff No question in particular, i'd like to see how to properly use typescript with react/redux. Maybe with something else than a simple todo-app
@@hswolff How to handle null and undefined in TS, how to remove nulls from a type with type guards and such but more in advanced
Your english is easy to understand for me! Thank you.
Why not use just string literals like type Colors = 'blue' | 'green'? Any drawbacks comprising with the code you have just shown?
That’s not scalable, what If there were hundreds of key/value pairs in the object? Best to infer from the object itself
That's fine too! My pre-TS days always had me scared to use strings as they can be typo-d so easily, hence why I used objects to ensure there would never be any typos.
If you're in an entirely TS project then using enums or just a string union is 100% good! If you're interopting with JS libraries I may recommend also exporting an object to ensure no typos.
Also, context is everything! So pick what's best for what you need!
Let me tell you that you have the ability to teach me things in a easy way... Good job mate
So glad to hear!
How can a simple concept like enums be so complicated in TypeScript ? 😒
So many of these tutorials forget to mention that enums is an example of the glyph pattern such that is is flexible to what is represented
This is a great video! Fundamental idea and no one is describing it as clearly as you. Great Job and thank you.
Hmm, enums seem to me like they have a lot of complexity and there's a lot of room to screw things up. Whereas doing something like `type Color = 'blue' | 'green'`, there's not really that room for error. So I see that as a downside to enums, and I'm not really sure what the upside is, nor when that upside would ever outweigh the downside. Can anyone help me understand this?
hey what happens if you have an object `triangle` with a property `color`i.e ```let triangle= { color: Color }```, and in your `showColor` function you set triangle.color = color ???
Great video! Can you please go into more detail why in general you would not recommend using enums/ const enums for libraries?
why does this works... type Colors and const Colors have the same variable name. How does type script identify those 2 variables. Please help.
Oh wow, this is funny.
I used to be a user (and small contributor) to Reptar back in the day. I didn't know that you had a RUclips channel. :D
Exactly what I’ve been struggling with a few days ago, while trying to type some json properties. I think I ended up casting them. Tomorrow I’ll refactor them the correct way.
I told you this before some time ago, your content is sorely missed. Are you writing something at mongo? Are you speaking at any conferences? 🤞
Great content, as usual, Harry!
TypeScript is a really nice technology. In the beginning it can be difficult to see its benefits, I'd say, because you lose the agility that dynamic languages give you. But once you start to be more comfortable with TypeScript, it's very clear how many errors it prevents you from making.
Go ahead with your videos, man, they are fantastic! :)
Very well said about learning TS! Def a learning curve but def worth it when you learn it.
Thank you for the kind words!
At 3:35 you can fix your error at line 17 by telling TS you're sure of what you're doing using the operator 'as'
showColor('blue' as Colors)
What do I do if I want to pass a string instance to the showColor(color: Colors) function? as in:
const myColor: string = "blue";
showColor(myColor);
Typescript is giving me an error in the IDE but the code seems to produce the desired result.
You can probably do something like:
showColor(myColor as Colors);
But this also allows you to pass in an invalid color as well. I'd love to know if there is a way to avoid that.
Harry,
Thank you for all the content that you make. This was informative and clear.
You are very welcome! Thank you for watching!
An interesting balance, I think I sit on "prefer const objects over enums when you can" also - there's occasionally some movement on real JS enums from tc39, but it's still a long way off and who knows if the semantics will be the same,
Hey Orta!! I'm so glad we agree :)
I'm not even going to hold my breath for enums being added to JS. That is a pipedream's pipe dream.
8:18 A type with the same name as a value?
Would love a revisit of this. Especially with `unknown` types!
I ran into this exact issue and ended up casting each object property as itself, so Blue: “blue” as “blue” - this seems cleaner though
You want to use `as const`! It's a lovely shortcut!
Does this handle type checking that the values are correct? My typescript compiler just indicates that color is a string... :/
whoops! forget the as const
Is there any way to do same as for const but with enum?
Super clean and easy-understanding code. Love type script!
Woohoo!! Thank you!
Is there really any major benefit to this opposed to solely using a string union type?
IMO mostly when interopting with JS libraries and you want to make sure there's no string typos on the value.
If you're in an entirely TS only library then use enums and string unions with wild abandon!
wait, wait, wait. you exported Colors as a type and as an Object. how is that possible? so when I import I would do `import { Colors } from 'colors'`. What would I get there? Colors the type or the const Object???!! I'm super confused here.
Devils advocate...
Doesn't this kind of negate the purpose of enums a bit? I always thought that enums were supposed to be kind of a constraint on the values you can use and that is exactly why you use them. They force you to use predefined values. It may be more convenient to just use a string, 'blue', but you are asking for trouble if the desired string is not in your enum. Sure you will get an error that tells you the value is not allowed, but if you use the Colors.Blue you are guaranteed the value is valid. Additionally, you should get intellisense (or equiv) listing all of your options within the enum.
Not looking to pick a fight :) but why a workaround on enums?
Amazing! Thanks for the video!
Awesome, thx for showing this! Would it not make more sense to name the type as singular tho?
Yeah probably! Dealer's choice though tho.
Probably less confusing to use exported constants and put those in an array as const.
Beast. Love your content
Great video Harry, really well explained.
Thank you!
Hey Harry, great content. Would you be able to make a useReducer with TS video? I looked in the docs and couldn't find any information about it.
Oh snap, that's a great idea! I shall add it to my list, thank you!
typeof keyof typeof I think this is really not readable and feels hacky overal. Defeating the whole purpose of Typescript with this spaghetti type gymnastics.
Yeah it's definitely a little gross, but unfortunately there's no other way that I know how to do it. I'd love to know of a better way but that's the way I know so far.
thanks for this videos ! you're saving my life
One video at a time 👹
simply amazing, thank you!
Eyy, thank you! Glad you liked!
Great video and nice explanation
Thank you so much!
This great Harry thanks
You are very welcome!
Hey Harry. Boy, you've done it again -- constantly raising the bar for us all -- and doing it flawlessly. I'd say I'm surprised, but I know who you are. (Michelle Obama reference)
Lol what's the reference? I missed it 😵 Thanks for the kind words as always! Glad the video was a hit!
Harry Wolff ruclips.net/video/i0dmSIAzWeQ/видео.html 😂😂😂 I like your code style! I personally want to see a simple Full Stack app!
more TS videos please|
It's complicated, I could not understand this... ;(
Did you just give me another reason not to bother with TS... thank you good sir 🙏🏻 ☺️
Haha...this was mostly to encourage one pattern of usage when you use TS. TS itself is fine! Just gotta deal with that learning curve 🙈
Harry Wolff my brain is getting low on writable byte storage 😏
wow!! mind-blown. Thanks!!.... But i still kinda hate TS... haha
Let me be amongst the millions of people that have undoubtedly also said that your name is pretty b'dass. Also, thanks for the content.
1.5 speed, dude is still slow.
that's why you have speed x2 ;)
f typescript