as const: the most underrated TypeScript feature

Поделиться
HTML-код
  • Опубликовано: 28 июн 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
  • НаукаНаука

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

  • @TechnologicNick
    @TechnologicNick 10 месяцев назад +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 10 месяцев назад +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 8 месяцев назад +3

      The template literal trick is mind blowing!

  • @weirdwordcombo
    @weirdwordcombo 10 месяцев назад +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 10 месяцев назад +23

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

    • @Ma1ne2
      @Ma1ne2 10 месяцев назад

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

    • @willshadow
      @willshadow 10 месяцев назад

      holy crap I needed this, tysm

  • @goncaloflorencio6529
    @goncaloflorencio6529 10 месяцев назад +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.

  • @apina2
    @apina2 10 месяцев назад +45

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

    • @zuma206
      @zuma206 Месяц назад +5

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

  • @nadavrot
    @nadavrot 10 месяцев назад +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 10 месяцев назад +3

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

  • @waterbreak
    @waterbreak 10 месяцев назад +2

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

  • @ColinRichardson
    @ColinRichardson 10 месяцев назад +80

    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 10 месяцев назад +4

      PS: Where is the Top hat and Monocle?

    • @SimGunther
      @SimGunther 10 месяцев назад

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

  • @josephsliman3395
    @josephsliman3395 10 месяцев назад +1

    I love your typescript content, thanks

  • @uicornerwithJ
    @uicornerwithJ 9 месяцев назад

    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.

  • @AlessioMichelini
    @AlessioMichelini 10 месяцев назад

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

  • @Gustavewpm
    @Gustavewpm 3 месяца назад

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

  • @naraksama3903
    @naraksama3903 10 месяцев назад +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 10 месяцев назад +1

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

    • @naraksama3903
      @naraksama3903 10 месяцев назад

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

  • @mattinpjs
    @mattinpjs 10 месяцев назад

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

  • @hatchibomb
    @hatchibomb 10 месяцев назад

    Amazing! I needed this earlier today!

  •  10 месяцев назад

    The best and simplest explanation of "as const"!

  • @JDalmasca
    @JDalmasca 10 месяцев назад

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

  • @adi96adi
    @adi96adi 5 месяцев назад

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

  • @nixoncode
    @nixoncode 10 месяцев назад

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

  • @rizkyagungprasetyo8293
    @rizkyagungprasetyo8293 10 месяцев назад +6

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

  • @TheGrandChieftain
    @TheGrandChieftain 10 месяцев назад +1

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

  • @DC-xt1ry
    @DC-xt1ry 10 месяцев назад

    Very nice ticks! keep them comming sensei!

  • @brad8961
    @brad8961 10 месяцев назад

    Videos are very useful and clear, thanks

  • @Nabulio85
    @Nabulio85 10 месяцев назад

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

  • @williamlvea
    @williamlvea 10 месяцев назад +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

  • @grandpowr
    @grandpowr 10 месяцев назад

    Thank you very much Mr Matt!

  • @AudaiAlFandi
    @AudaiAlFandi 10 месяцев назад

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

  • @yoni532s9M5w
    @yoni532s9M5w 10 месяцев назад +1

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

  • @ginger-viking
    @ginger-viking 10 месяцев назад

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

  • @somewonderfulguy
    @somewonderfulguy 9 месяцев назад

    Watched small video - huge power acquired. Thank you!

  • @giodefreitas
    @giodefreitas 10 месяцев назад

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

  • @aamiramin6112
    @aamiramin6112 10 месяцев назад

    Amazing so concise and clean.

  • @AbWischBar
    @AbWischBar 10 месяцев назад

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

  • @griffadev
    @griffadev 10 месяцев назад +1

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

  • @melvins126
    @melvins126 10 месяцев назад

    Made me subscribe. Thank you very much. 👍

  • @leesasuki
    @leesasuki 5 месяцев назад

    thank you, you are a life saver!

  • @PraiseYeezus
    @PraiseYeezus 10 месяцев назад

    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.

  • @Hadi-gd7ul
    @Hadi-gd7ul 10 месяцев назад

    This is so beautiful that i want to cry.

  • @skandertebourbi357
    @skandertebourbi357 10 месяцев назад

    Simply a typescript magician

  • @olegsbk3562
    @olegsbk3562 10 месяцев назад +2

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

  • @Dmitri_Ivanovich
    @Dmitri_Ivanovich 10 месяцев назад

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

  • @Rivernile345
    @Rivernile345 10 месяцев назад

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

  • @christopheradolphe
    @christopheradolphe 3 месяца назад

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

  • @stephanfitzpatrick1769
    @stephanfitzpatrick1769 5 месяцев назад

    Brilliant. Instant follow

  • @Leon-xg7zj
    @Leon-xg7zj 10 месяцев назад

    Awesome sharing!

  • @zb2747
    @zb2747 10 месяцев назад +1

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

  • @irfanfauzi8704
    @irfanfauzi8704 3 месяца назад

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

    • @wiktorchojnacki9746
      @wiktorchojnacki9746 2 месяца назад

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

  • @robertmengual8357
    @robertmengual8357 10 месяцев назад

    Great video, typescript is beautiful

  • @VolodymyrEisenhorn
    @VolodymyrEisenhorn 10 месяцев назад

    Just wow. Thank you.

  • @PapitaPure
    @PapitaPure Месяц назад

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

  • @sergey_llal6897
    @sergey_llal6897 9 месяцев назад +2

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

  • @maxwebstudio
    @maxwebstudio 10 месяцев назад

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

  • @alexeypetrov8543
    @alexeypetrov8543 10 месяцев назад

    That's brilliant!

  • @aram5642
    @aram5642 9 месяцев назад

    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!

  • @MightyKingKala
    @MightyKingKala 10 месяцев назад

    this video is amazing!

  • @DoorThief
    @DoorThief 12 дней назад

    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.

    • @anonymoususer520
      @anonymoususer520 5 дней назад

      The difference is that reflection happens at runtime. This "as const" typing happens statically at compile time, so it's typesafe -- unlike reflection.
      On the other hand, typescript types are not reified, whereas .net types are. So reflection over typescript types isn't possible, because the type information is erased during compilation.

  • @RockTheCage55
    @RockTheCage55 10 месяцев назад

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

  • @dawid_dahl
    @dawid_dahl 10 месяцев назад

    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.

  • @sc76399
    @sc76399 10 месяцев назад

    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

  • @thekaasim
    @thekaasim 10 месяцев назад

    helpful video. thanks.

  • @lalumierehuguenote
    @lalumierehuguenote 10 месяцев назад

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

  • @user-hk6ns2eg1w
    @user-hk6ns2eg1w 6 месяцев назад

    Nice!! thanks

  • @wattsfield1889
    @wattsfield1889 10 месяцев назад

    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

  • @osamanajjar1934
    @osamanajjar1934 10 месяцев назад

    Matt the goat!

  • @rockNbrain
    @rockNbrain 10 месяцев назад

    Nice job 🎉

  • @Mujahedeen_
    @Mujahedeen_ 10 месяцев назад

    YOU are the most underrated RUclipsr

  • @maxwebstudio
    @maxwebstudio 10 месяцев назад

    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 ?

  • @micelumail5829
    @micelumail5829 10 месяцев назад +1

    4:05 me knowing new ts magic

  • @zuperxtreme
    @zuperxtreme 10 месяцев назад +3

    Would an enum work the same?

    • @punsmith
      @punsmith 10 месяцев назад

      It would, but Matt has an irrational hatred for them, as seen in one of his videos "Why you shouldn't use Enums". Watch him abuse the concept of Enums and instead using magic variables. Biggest tool I've seen in TS.

  • @StephenRayner
    @StephenRayner 10 месяцев назад

    Beautiful

  • @moneyfr
    @moneyfr 10 месяцев назад +3

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

    • @joaofrancisco5781
      @joaofrancisco5781 10 месяцев назад +1

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

  • @shane3744
    @shane3744 10 месяцев назад +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.

  • @Orenrs
    @Orenrs 10 месяцев назад

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

    • @mattpocockuk
      @mattpocockuk  10 месяцев назад

      Check my video on enums

    • @3453wer
      @3453wer 6 месяцев назад

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

  • @rhodler
    @rhodler Месяц назад

    Merci !

  • @ThanHtutZaw3
    @ThanHtutZaw3 5 месяцев назад

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

  • @danielratiu4318
    @danielratiu4318 6 месяцев назад

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

  • @prashantjoshi6703
    @prashantjoshi6703 10 месяцев назад +2

    But what benefit it adds in comparison to string enums?🥺

    • @scylk
      @scylk 10 месяцев назад +1

      Wondering the same lol

  • @mbenlahrech
    @mbenlahrech 6 месяцев назад

    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

  • @lambgoat2421
    @lambgoat2421 5 месяцев назад

    Finally something from youtube I will actually use

  • @segen8324
    @segen8324 10 месяцев назад

    this is beautiful

  • @alexking7684
    @alexking7684 10 месяцев назад

    Fenomenal! 🎉

  • @furkan7013
    @furkan7013 10 месяцев назад

    Anybody knows that translation plugin for error messages ?

  • @omkarbhale442
    @omkarbhale442 10 месяцев назад +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 10 месяцев назад

      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 10 месяцев назад +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 10 месяцев назад

      @@programming5274 Yes!

    • @punsmith
      @punsmith 10 месяцев назад

      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 6 месяцев назад

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

  • @Alec.Vision
    @Alec.Vision 10 месяцев назад

    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 🤷

  • @jpgarcia90
    @jpgarcia90 6 месяцев назад

    What's the different between this and using Enums?

  • @lorenzorev
    @lorenzorev 4 месяца назад

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

  • @josemfcheo
    @josemfcheo 5 месяцев назад

    this is awesome

  • @barneylaurance1865
    @barneylaurance1865 10 месяцев назад

    So if you want as const but you don't want the whole tamale const you can define the internal object first as standard mutable object, and then put it inside in the outer const object.
    I.e. if you have
    const deep = {
    whatever: "/deep/whatever",
    };
    const routes = {
    admin: "/admin",
    home: "/",
    deep: deep,
    } as const;
    then routes will be inferred as of type:
    {
    readonly admin: "/admin";
    readonly home: "/";
    readonly deep: {
    whatever: string;
    };
    }

  • @user-qk2nl8lf9y
    @user-qk2nl8lf9y 10 месяцев назад

    what is the VSCode extension you're using to get the human-readable ts error messages?

    • @mattpocockuk
      @mattpocockuk  10 месяцев назад

      www.totaltypescript.com/vscode-extension

    • @user-qk2nl8lf9y
      @user-qk2nl8lf9y 10 месяцев назад

      @@mattpocockuk Thanks so much!

  • @am29d
    @am29d 10 месяцев назад

    Mind blowing...

  • @latituddev7884
    @latituddev7884 10 месяцев назад

    what is that extension that translates ts errors i need it

    • @zapxcero
      @zapxcero 4 месяца назад

      probably Total Typescript

  • @spencereaston8292
    @spencereaston8292 10 месяцев назад

    And this is because, I am assuming from the pop-up, enums should not be used?

  • @vrtech473
    @vrtech473 10 месяцев назад

    never knew this 😂😂😂😂 GOAT🎉🎉

  • @mananabanana
    @mananabanana 10 месяцев назад +7

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

  • @yes.daniel
    @yes.daniel 10 месяцев назад

    yes!

  • @AlfredLotsu
    @AlfredLotsu 9 месяцев назад

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

  • @kelvindecosta5350
    @kelvindecosta5350 10 месяцев назад

    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 10 месяцев назад

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

  • @tobbymarchal3140
    @tobbymarchal3140 10 месяцев назад

    How to use for array

  • @MrTrevorrrrrrrr
    @MrTrevorrrrrrrr 10 месяцев назад

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