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/

Комментарии • 81

  • @DavimDantas
    @DavimDantas 4 года назад +14

    You could have created a help type:
    type ValueOf = T[keyof T];
    type Colors = ValueOf

    • @devagr
      @devagr 4 года назад +2

      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.

  • @dandcodes
    @dandcodes 4 года назад +16

    I love this type of content, more TS videos please!

    • @hswolff
      @hswolff  4 года назад

      Woohoo! So glad you liked this!

  • @jonathanolson1764
    @jonathanolson1764 3 года назад +1

    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

    • @hswolff
      @hswolff  3 года назад

      That’s so heartening to hear! Glad it helped!

  • @NomadeDigital
    @NomadeDigital 4 года назад +3

    Mind blown, I love where the channel is going lately, Deno, typescript and Rust ? Yes please !

    • @hswolff
      @hswolff  4 года назад

      All the type safety, all the time! :D

  • @Deliverant
    @Deliverant 4 года назад +15

    More TypeScript content pleeease, maybe with react/redux would be top

    • @hswolff
      @hswolff  4 года назад

      What questions do you have?

    • @Deliverant
      @Deliverant 4 года назад +1

      ​@@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

    • @titogoda
      @titogoda 4 года назад

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

  • @personagenscantandoraps
    @personagenscantandoraps 2 года назад +1

    Your english is easy to understand for me! Thank you.

  • @sergeyzwezdin
    @sergeyzwezdin 4 года назад +2

    Why not use just string literals like type Colors = 'blue' | 'green'? Any drawbacks comprising with the code you have just shown?

    • @danb8610
      @danb8610 4 года назад

      That’s not scalable, what If there were hundreds of key/value pairs in the object? Best to infer from the object itself

    • @hswolff
      @hswolff  4 года назад +1

      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!

  • @rafaelcalderon6658
    @rafaelcalderon6658 3 года назад +1

    Let me tell you that you have the ability to teach me things in a easy way... Good job mate

    • @hswolff
      @hswolff  3 года назад +1

      So glad to hear!

  • @bgdnsr
    @bgdnsr 4 года назад +3

    How can a simple concept like enums be so complicated in TypeScript ? 😒

  • @SchkuenteQoostewin
    @SchkuenteQoostewin 3 года назад

    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

  • @brycejackson2065
    @brycejackson2065 Год назад

    This is a great video! Fundamental idea and no one is describing it as clearly as you. Great Job and thank you.

  • @adamzerner5208
    @adamzerner5208 2 года назад

    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?

  • @kamalsomani285
    @kamalsomani285 2 года назад

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

  • @matthiaslang6750
    @matthiaslang6750 4 года назад +2

    Great video! Can you please go into more detail why in general you would not recommend using enums/ const enums for libraries?

  • @yanlinli1146
    @yanlinli1146 2 года назад

    why does this works... type Colors and const Colors have the same variable name. How does type script identify those 2 variables. Please help.

  • @WorstDeveloper
    @WorstDeveloper 2 года назад

    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

  • @sashaikevich
    @sashaikevich Год назад

    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? 🤞

  • @evandroLG2
    @evandroLG2 4 года назад

    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! :)

    • @hswolff
      @hswolff  4 года назад

      Very well said about learning TS! Def a learning curve but def worth it when you learn it.
      Thank you for the kind words!

  • @tntg5
    @tntg5 2 года назад

    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)

  • @nizostyle
    @nizostyle 4 года назад +1

    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.

    • @mahendrathennakoon6482
      @mahendrathennakoon6482 2 года назад

      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.

  • @jhonatanparedes7198
    @jhonatanparedes7198 4 года назад

    Harry,
    Thank you for all the content that you make. This was informative and clear.

    • @hswolff
      @hswolff  4 года назад

      You are very welcome! Thank you for watching!

  • @ortatherox
    @ortatherox 4 года назад

    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,

    • @hswolff
      @hswolff  4 года назад

      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.

  • @MichaelSalo
    @MichaelSalo 2 года назад

    8:18 A type with the same name as a value?

  • @r-i-ch
    @r-i-ch 3 года назад

    Would love a revisit of this. Especially with `unknown` types!

  • @danb8610
    @danb8610 4 года назад

    I ran into this exact issue and ended up casting each object property as itself, so Blue: “blue” as “blue” - this seems cleaner though

    • @hswolff
      @hswolff  4 года назад +1

      You want to use `as const`! It's a lovely shortcut!

  • @someonlinevideos
    @someonlinevideos Год назад

    Does this handle type checking that the values are correct? My typescript compiler just indicates that color is a string... :/

  • @sLavoncheg
    @sLavoncheg 2 года назад

    Is there any way to do same as for const but with enum?

  • @aksyonov100
    @aksyonov100 4 года назад

    Super clean and easy-understanding code. Love type script!

    • @hswolff
      @hswolff  4 года назад

      Woohoo!! Thank you!

  • @joshhwb
    @joshhwb 4 года назад +1

    Is there really any major benefit to this opposed to solely using a string union type?

    • @hswolff
      @hswolff  4 года назад +1

      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!

  • @nafaabout
    @nafaabout Год назад

    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.

  • @willcalltickets
    @willcalltickets 3 года назад +1

    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?

  • @antonjust3503
    @antonjust3503 3 года назад

    Amazing! Thanks for the video!

  • @davidjensen6215
    @davidjensen6215 4 года назад +1

    Awesome, thx for showing this! Would it not make more sense to name the type as singular tho?

    • @hswolff
      @hswolff  4 года назад +1

      Yeah probably! Dealer's choice though tho.

  • @Diamonddrake
    @Diamonddrake 3 года назад

    Probably less confusing to use exported constants and put those in an array as const.

  • @xtsxo9872
    @xtsxo9872 Год назад

    Beast. Love your content

  • @webhedz
    @webhedz 4 года назад

    Great video Harry, really well explained.

  • @Dgiulian
    @Dgiulian 4 года назад

    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.

    • @hswolff
      @hswolff  4 года назад

      Oh snap, that's a great idea! I shall add it to my list, thank you!

  • @jermainebrayne437
    @jermainebrayne437 4 года назад +2

    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.

    • @hswolff
      @hswolff  4 года назад

      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.

  • @juanbarman
    @juanbarman 4 года назад

    thanks for this videos ! you're saving my life

    • @hswolff
      @hswolff  4 года назад

      One video at a time 👹

  • @davidesantimaria8018
    @davidesantimaria8018 4 года назад

    simply amazing, thank you!

    • @hswolff
      @hswolff  4 года назад

      Eyy, thank you! Glad you liked!

  • @omar9ali
    @omar9ali 4 года назад

    Great video and nice explanation

    • @hswolff
      @hswolff  4 года назад

      Thank you so much!

  • @ChristopherPhillips
    @ChristopherPhillips 3 года назад

    This great Harry thanks

    • @hswolff
      @hswolff  3 года назад

      You are very welcome!

  • @seanaguinaga
    @seanaguinaga 4 года назад

    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)

    • @hswolff
      @hswolff  4 года назад +1

      Lol what's the reference? I missed it 😵 Thanks for the kind words as always! Glad the video was a hit!

    • @seanaguinaga
      @seanaguinaga 4 года назад

      Harry Wolff ruclips.net/video/i0dmSIAzWeQ/видео.html 😂😂😂 I like your code style! I personally want to see a simple Full Stack app!

  • @rucklerful
    @rucklerful 4 года назад

    more TS videos please|

  • @trader9559
    @trader9559 4 года назад

    It's complicated, I could not understand this... ;(

  • @everyhandletaken
    @everyhandletaken 4 года назад +2

    Did you just give me another reason not to bother with TS... thank you good sir 🙏🏻 ☺️

    • @hswolff
      @hswolff  4 года назад +4

      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 🙈

    • @everyhandletaken
      @everyhandletaken 4 года назад

      Harry Wolff my brain is getting low on writable byte storage 😏

  • @raymondtam8107
    @raymondtam8107 4 года назад

    wow!! mind-blown. Thanks!!.... But i still kinda hate TS... haha

  • @erickgeneric
    @erickgeneric 2 года назад

    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.

  • @paulvbarbar9957
    @paulvbarbar9957 3 года назад

    1.5 speed, dude is still slow.

    • @morngrim2
      @morngrim2 3 года назад

      that's why you have speed x2 ;)

  • @nested9301
    @nested9301 8 месяцев назад

    f typescript