as const: the most underrated TypeScript feature

Sdílet
Vložit
  • čas přidán 20. 06. 2024
  • 'as const' is an amazingly useful TypeScript feature that most people still don't know about.
    00:00 SO underrated
    00:12 Objects are mutable!
    01:54 How as const works
    02:38 Object.freeze
    03:19 Deriving types from as const
    04:30 keyof typeof
    Become a TypeScript Wizard with my free beginners TypeScript Course:
    www.totaltypescript.com/tutor...
    Follow Matt on Twitter
    / mattpocockuk
    Join the Discord:
    mattpocock.com/discord
  • Věda a technologie

Komentáře • 307

  • @TechnologicNick
    @TechnologicNick Před 10 měsíci +95

    You can also use `as const` on individual value literals or use it on template string literals to get all possible strings.

    • @ElektrykFlaaj
      @ElektrykFlaaj Před 10 měsíci +9

      or on array to get a tuple. For instance typeof (["a", 1] as const) is readonly ["a", 1], while typeof ["a", 1] is (string | number)[]

    • @cool_scatter
      @cool_scatter Před 7 měsíci +3

      The template literal trick is mind blowing!

  • @weirdwordcombo
    @weirdwordcombo Před 10 měsíci +46

    Metadata based programming can be very very powerful. It essentially allows you to expand an application by just adding metadata to an object, while also writing less code overall. I have found that old codebasis often have similar and/or duplicate code all over the place, which can be refactored with this metadata based driven approach. Cuts down on TONS of boilerplate.

  • @leotravel85
    @leotravel85 Před 10 měsíci +23

    You can also use 'satisfies' with 'as const' to constraint the object typings, like 'as const satisfies Record', its super neat

    • @Ma1ne2
      @Ma1ne2 Před 10 měsíci

      Damn I needed this so many times and didn't know about it, thanks for sharing.

    • @willshadow
      @willshadow Před 10 měsíci

      holy crap I needed this, tysm

  • @apina2
    @apina2 Před 10 měsíci +43

    "const as const"
    sounds really smart and not ridiculous at all

    • @zuma206
      @zuma206 Před měsícem +5

      It makes perfect sense within the typescript syntax, and it's relationship with javascript syntax

  • @goncaloflorencio6529
    @goncaloflorencio6529 Před 10 měsíci +15

    Thanks a lot for this longer explanation! I sometimes have a harder time catching up on the really short videos but here I was able to get everything immediately.

  • @ColinRichardson
    @ColinRichardson Před 10 měsíci +79

    I use this quite often, I don't think it's underrated, I think other things may just be rated too highly... LOL

    • @ColinRichardson
      @ColinRichardson Před 10 měsíci +4

      PS: Where is the Top hat and Monocle?

    • @SimGunther
      @SimGunther Před 10 měsíci

      ​@@ColinRichardsonPeople do wear two monocles to make a _spectacle_ for themselves, so now he's just missing the top hat, old chap 🎩

  • @nadavrot
    @nadavrot Před 10 měsíci +11

    Excellent video! You often make videos about bleeding edge TS features (that I can’t use yet) or incredibly complex topics (that make me scratch my head) but this video was super accessible and easy to follow! Here’s hoping you will make more mid-level TS concepts videos.

  • @DulithMutucumarana
    @DulithMutucumarana Před 10 měsíci +3

    Awesome! Thanks!
    works on arrays as well:
    const abc = ['a', 'b', 'c'] as const;
    type ABC = typeof abc[number];

  • @waterbreak
    @waterbreak Před 10 měsíci +2

    After watching half of the video, I found an immediate use case in my TS project I'm working on. Great video!

  • @uicornerwithJ
    @uicornerwithJ Před 9 měsíci

    Thank you sir for this great explanation. I am glad that there are so passionate typescript writers out there like yourself. Just watching this video made me understand the keyof typeof stuff and as const much easier.

  • @josephsliman3395
    @josephsliman3395 Před 10 měsíci +1

    I love your typescript content, thanks

  • @AlessioMichelini
    @AlessioMichelini Před 10 měsíci

    That's absolutely brilliant! I wasn't super sure what "as const" was doing, thanks for clarifying that!

  • @Gustavewpm
    @Gustavewpm Před 2 měsíci

    Amazing video.
    Such really good pedagogy, loved it, even if I was already very familiar with as const and the other notions sumed up.

  • @JDalmasca
    @JDalmasca Před 10 měsíci

    Just came to say this video finally helped make `as const` click for me. Thanks for the info, Matt!

  • @mattinpjs
    @mattinpjs Před 10 měsíci

    This is such a helpful feature. I'll be using this all the time now, thank you

  • @DoorThief
    @DoorThief Před 4 dny

    As someone who doesn't know TS and just knows C#, I recoiled slightly when I saw the keyof typeof [] bit
    But then I remembered reflection is pretty much like that anyways in C#, accessing public (or private) members and the like.

  •  Před 10 měsíci

    The best and simplest explanation of "as const"!

  • @hatchibomb
    @hatchibomb Před 10 měsíci

    Amazing! I needed this earlier today!

  • @naraksama3903
    @naraksama3903 Před 10 měsíci +2

    I love as const so much. It gives so much information of the code base you're trying to work with. It's makes localization strings global constants so much more useable.

    • @scylk
      @scylk Před 10 měsíci +1

      Hey can you expand a little bit on that? Sounds interesting

    • @naraksama3903
      @naraksama3903 Před 10 měsíci

      @@scylk It's very simple. You create an object that basically stores all of your strings and add an handler to dynamically change it based on the users OS language. When you mark those strings as const, TypeScript still sees the values of your default language and it's easier to know what string represents what text.

  • @adi96adi
    @adi96adi Před 5 měsíci

    Needed this a few months ago 😂 excellent content on this channel dude keep it up

  • @nixoncode
    @nixoncode Před 10 měsíci

    i was in a live stream a few days ago on this,learned so much

  • @TheGrandChieftain
    @TheGrandChieftain Před 10 měsíci +1

    Was using an enum for a radio group in Zod and discovered this. Never went through the trouble of understanding it, though. Thanks 👍🏿

  • @brad8961
    @brad8961 Před 10 měsíci

    Videos are very useful and clear, thanks

  • @DC-xt1ry
    @DC-xt1ry Před 10 měsíci

    Very nice ticks! keep them comming sensei!

  • @Nabulio85
    @Nabulio85 Před 10 měsíci

    Really great.
    You are a great teacher 😊
    Thx from France.

  • @yoni532s9M5w
    @yoni532s9M5w Před 10 měsíci +1

    That's worthy of a medium article mate. Very nice solution to a very popular recurring problem

  • @grandpowr
    @grandpowr Před 10 měsíci

    Thank you very much Mr Matt!

  • @AudaiAlFandi
    @AudaiAlFandi Před 10 měsíci

    Finally... now I understand it. Thank you Matt.

  • @somewonderfulguy
    @somewonderfulguy Před 9 měsíci

    Watched small video - huge power acquired. Thank you!

  • @irfanfauzi8704
    @irfanfauzi8704 Před 2 měsíci

    It's ridiculous that I can't expect const as constant value. Love your vids

    • @wiktorchojnacki9746
      @wiktorchojnacki9746 Před 2 měsíci

      You can, you just need to know what is constant about your value.

  • @giodefreitas
    @giodefreitas Před 9 měsíci

    This channel is also underrated. awesome video! you just got a new subscriber here

  • @rizkyagungprasetyo8293
    @rizkyagungprasetyo8293 Před 10 měsíci +6

    Sometimes I utilize this tool to manage database names, collections, roles, etc., enabling me to infer values instead of strings :).

  • @ginger-viking
    @ginger-viking Před 10 měsíci

    I did not know as const prevented the object being changed - thanks!

  • @aamiramin6112
    @aamiramin6112 Před 10 měsíci

    Amazing so concise and clean.

  • @AbWischBar
    @AbWischBar Před 10 měsíci

    That was a whole lot of fantastic stuff that will immediately be used

  • @Leon-xg7zj
    @Leon-xg7zj Před 9 měsíci

    Awesome sharing!

  • @christopheradolphe
    @christopheradolphe Před 3 měsíci

    Awesome tip here. Thank you @mattpocockuk for sharing this.

  • @melvins126
    @melvins126 Před 10 měsíci

    Made me subscribe. Thank you very much. 👍

  • @Rivernile345
    @Rivernile345 Před 10 měsíci

    Wow great video especially as a new typescript developer, I subscribed

  • @skandertebourbi357
    @skandertebourbi357 Před 10 měsíci

    Simply a typescript magician

  • @Dmitri_Ivanovich
    @Dmitri_Ivanovich Před 10 měsíci

    "Object.values on a type level" trick is pretty neat. Thanks!

  • @williamlvea
    @williamlvea Před 10 měsíci +3

    The biggest issue I've had with 'as const' is that it doesn't play well with libraries. Because of the readonly you'll get into cases where libraries are expected something like string[] and will require casting to mask the readonly.
    It also doesn't actually freeze the values, which can cause hard to debug bugs

  • @Hadi-gd7ul
    @Hadi-gd7ul Před 10 měsíci

    This is so beautiful that i want to cry.

  • @stephanfitzpatrick1769
    @stephanfitzpatrick1769 Před 4 měsíci

    Brilliant. Instant follow

  • @PraiseYeezus
    @PraiseYeezus Před 10 měsíci

    You guys are lucky I'm dumb, I asked the question that inspired this video :)
    Thanks for all you do Matt, I learned a whole lot.

  • @leesasuki
    @leesasuki Před 4 měsíci

    thank you, you are a life saver!

  • @robertmengual8357
    @robertmengual8357 Před 10 měsíci

    Great video, typescript is beautiful

  • @zb2747
    @zb2747 Před 10 měsíci +1

    I love your videos. Very insightful, fun, and straight to the point

  • @griffadev
    @griffadev Před 10 měsíci +1

    Nice video! Heads up on this format on mobile because there's no CZcams outro, the "suggested video" card appeared whilst you were still coding and blocked the code in video

  • @PapitaPure
    @PapitaPure Před měsícem

    You just saved me wtf. I was looking for a solution like this yesterday

  • @VolodymyrEisenhorn
    @VolodymyrEisenhorn Před 10 měsíci

    Just wow. Thank you.

  • @alexeypetrov8543
    @alexeypetrov8543 Před 10 měsíci

    That's brilliant!

  • @MightyKingKala
    @MightyKingKala Před 10 měsíci

    this video is amazing!

  • @maxwebstudio
    @maxwebstudio Před 10 měsíci

    Niiiiice ! I always forget how to target the type of keys and values of objects 😅

  • @thekaasim
    @thekaasim Před 10 měsíci

    helpful video. thanks.

  • @Mujahedeen_
    @Mujahedeen_ Před 10 měsíci

    YOU are the most underrated CZcamsr

  • @osamanajjar1934
    @osamanajjar1934 Před 10 měsíci

    Matt the goat!

  • @rockNbrain
    @rockNbrain Před 10 měsíci

    Nice job 🎉

  • @lambgoat2421
    @lambgoat2421 Před 5 měsíci

    Finally something from youtube I will actually use

  • @RockTheCage55
    @RockTheCage55 Před 10 měsíci

    Excellent....pretty cool. Thanks....

  • @olegsbk3562
    @olegsbk3562 Před 10 měsíci +2

    What do you prefer “as const” or enum in cases like in video?

  • @user-hk6ns2eg1w
    @user-hk6ns2eg1w Před 6 měsíci

    Nice!! thanks

  • @lalumierehuguenote
    @lalumierehuguenote Před 10 měsíci

    Oh cool! I knew it for array to union, but not for object to union. Thanks!

  • @wattsfield1889
    @wattsfield1889 Před 10 měsíci

    Nice. Theo made a similar video of why Enums are bad. He did something similar like this object as const, but his was a string array as const. And the type Route = typeof routeArray[number]. So the difference is whether or not you want a key name associated with the routes

  • @aram5642
    @aram5642 Před 9 měsíci

    Would you consider making a video/talk about the 'declare' keyword. While lurking into various .d.ts files I can spot all possible combinations of 'declare class', 'declare abstract class' (also: 'abstract class' alone). I have only used declare in typescript playground to mimic the existence of a function to make my types go trhough, but I can't get my head wrapped around real-life usage and how it is different from interfaces. Thanks!

  • @sergey_llal6897
    @sergey_llal6897 Před 9 měsíci +2

    Can we use enum for store routes and avoid create additional types?

  • @StephenRayner
    @StephenRayner Před 10 měsíci

    Beautiful

  • @mananabanana
    @mananabanana Před 10 měsíci +7

    "as const or how to implement a real enum in typescript" 😂

  • @shane3744
    @shane3744 Před 10 měsíci +1

    Nice quick dive into using "as const" with objects! I know it's a useful TypeScript feature when I find myself using it intuitively as I'm coding.

  • @dawid_dahl
    @dawid_dahl Před 10 měsíci

    Awesome explanation, thank you!
    Do you know if TS typesystem is Turing complete? Like the programming you can do at the type level like that? I bet it is.

  • @AlfredLotsu
    @AlfredLotsu Před 9 měsíci

    I now understand Rich Harris. We are packing up and moving to Jsdoc

  • @micelumail5829
    @micelumail5829 Před 10 měsíci +1

    4:05 me knowing new ts magic

  • @segen8324
    @segen8324 Před 10 měsíci

    this is beautiful

  • @alexking7684
    @alexking7684 Před 10 měsíci

    Fenomenal! 🎉

  • @patsy02
    @patsy02 Před 10 měsíci

    CZcams's suggested video box is hiding the end of your video

  • @rhodler
    @rhodler Před měsícem

    Merci !

  • @mbenlahrech
    @mbenlahrech Před 5 měsíci

    Now using rust and coming from c this is really funny to me how JS devs (i am a 4 years js/ts dev) go nuts with typing systems

  • @maxwebstudio
    @maxwebstudio Před 10 měsíci

    Question : But when compiled, the 'as const' Object won't be frozen to JS i guess. So, if it's for heap memory optimization it is better to freeze the object a long side 'as const', isn't it ?

  • @sc76399
    @sc76399 Před 10 měsíci

    As const is really cool. Didn't know we could do that. Is there not an easier way to get values of an object as a union? Like we have keys of us there not values of

  • @RevHardt
    @RevHardt Před 10 měsíci

    Can’t wait for languages to treat everything as const by default

  • @josemfcheo
    @josemfcheo Před 5 měsíci

    this is awesome

  • @am29d
    @am29d Před 10 měsíci

    Mind blowing...

  • @MrTrevorrrrrrrr
    @MrTrevorrrrrrrr Před 10 měsíci

    I may have agreed, but even better is the new const in generics feature.

  • @vrtech473
    @vrtech473 Před 10 měsíci

    never knew this 😂😂😂😂 GOAT🎉🎉

  • @ThanHtutZaw3
    @ThanHtutZaw3 Před 4 měsíci

    How can I type safe for api end point url for fetch ? Some of them will need query or other will need only body .

  • @moneyfr
    @moneyfr Před 10 měsíci +3

    You didn't talk about: "as const satisfies Record "

    • @joaofrancisco5781
      @joaofrancisco5781 Před 10 měsíci +1

      I started using a lot of "as const satisfies typeX", I'm creating a lib and it's helping me a lot

  • @sujanbasnet7868
    @sujanbasnet7868 Před 10 měsíci

    Sick.

  • @anasalhariri5474
    @anasalhariri5474 Před 6 měsíci

    Good to know thanks for sharing :) Like and new Sub

  • @l0g3sh
    @l0g3sh Před 4 měsíci

    In deed you are a Wizard

  • @yes.daniel
    @yes.daniel Před 10 měsíci

    yes!

  • @Orenrs
    @Orenrs Před 10 měsíci

    Great video and example.
    Why not using enum for this case ?

    • @mattpocockuk
      @mattpocockuk  Před 10 měsíci

      Check my video on enums

    • @3453wer
      @3453wer Před 6 měsíci

      @@mattpocockuk checked your vid about enums, so again - why dont just use enum for this case? cause enum with specified values transpiles to a simple obj as you had in your video

  • @omkarbhale442
    @omkarbhale442 Před 10 měsíci +5

    Why didnt you use enums for the routes? It looks like you only need one of the three routes at any moment. This particular example doesn't show use of as const i think. (I'm new to typescript so maybe I'm wrong, please correct me)

    • @programming5274
      @programming5274 Před 10 měsíci

      Right, why prefer the code in the video in place of a string enum? String enums are made for this, and they generate faster and generally smaller JS output.
      const enum Routes {
      Home = "/",
      Admin = "/admin",
      Users = "/users",
      }

    • @programming5274
      @programming5274 Před 10 měsíci +2

      /* String enum */
      const enum Routes {
      Home = "/",
      Admin = "/admin",
      Users = "/users",
      }
      const goToRoute = (route: Routes) => {
      console.log(route);
      }
      goToRoute(Routes.Home);
      console.log("----------------------");
      /* as const */
      const rts = {
      home: "/",
      admin: "/admin",
      user: "/users",
      } as const;
      type Rte = (typeof rts)[keyof typeof rts];
      const goToRt = (route: Rte) => {
      console.log(route);
      }
      goToRt(rts.home);

    • @omkarbhale442
      @omkarbhale442 Před 10 měsíci

      @@programming5274 Yes!

    • @punsmith
      @punsmith Před 10 měsíci

      Because Matt has a hate boner for them and prefers magic variables. Sharing a codebase with him can be only the first step of hell.

    • @oscargm1979
      @oscargm1979 Před 5 měsíci

      @@programming5274 I totally agree yet I supose it is just to show that we have that option too. Imho u end with objects from other devs everytime so maybe u can just put 'as const' on them instead of refactoring to enums other people's job, idk

  • @danielratiu4318
    @danielratiu4318 Před 5 měsíci

    How about routes with matching variables like '/users/:id' that match /users/3 ?

  • @edgeeffect
    @edgeeffect Před 10 měsíci

    I first got interested in Typescript just because I thought I'd get type-checking... and weak typing was the 1990's biggest mistake. All of this auto-completion stuff in VSCode came along later as just a delightful extra little gift.

  • @jpgarcia90
    @jpgarcia90 Před 6 měsíci

    What's the different between this and using Enums?

  • @kelvindecosta5350
    @kelvindecosta5350 Před 10 měsíci

    Hey Matt, I've come across a pattern that I think deserves a shorthand:
    type X = { a: string } | { b : number } // Non discriminated union
    const x : X = { a: "hello"}
    const a = !!x && 'a' in x ? x.a : undefined // works fine, but is somewhat verbose.
    const a = x?.a // errors out because 'a' doesn't exist on type { b: number}
    Is there a simpler way of picking x.a?

    • @forivall
      @forivall Před 10 měsíci

      Search for "ExclusifyUnion", there's a good stack overflow answer with an explanation

  • @rutabega306
    @rutabega306 Před 10 měsíci +1

    Almost as good as 'as any'!

  • @Gaijin101
    @Gaijin101 Před 10 měsíci +1

    const as const as const

  • @lorenzorev
    @lorenzorev Před 4 měsíci

    Normally I would an enum in this case like "enum routes" and avoid declaring the type. What do you think?

  • @Alec.Vision
    @Alec.Vision Před 10 měsíci

    The thing about 'as const', when not used on type parameters, is that it lies. The runtime object is, in fact, not readonly. You can get the same effect, with added runtime correctness, from Object.freeze. I consider this an extension of the 'One Source of Truth' ethos. 'as const' is, essentially, a type assertion.
    But I'm %100 guilty of using it everywhere so 🤷