as const: the most underrated TypeScript feature

Поделиться
HTML-код
  • Опубликовано: 4 фев 2025

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

  • @TechnologicNick
    @TechnologicNick Год назад +110

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

    • @ElektrykFlaaj
      @ElektrykFlaaj Год назад +13

      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 Год назад +3

      The template literal trick is mind blowing!

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

      This can really blow up :) I think typescript is smart about ultimately collapsing a type when it gets too big (something like a few thousand options) "hey, its just a string - don't go crazy now"

  • @weirdwordcombo
    @weirdwordcombo Год назад +53

    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 Год назад +33

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

    • @Ma1ne2
      @Ma1ne2 Год назад +1

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

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

      holy crap I needed this, tysm

  • @goncaloflorencio6529
    @goncaloflorencio6529 Год назад +17

    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.

  • @alanwakeup3344
    @alanwakeup3344 17 дней назад

    Just started picking up TypeScript and your videos are really clear and concise, thank you.

  • @apina2
    @apina2 Год назад +78

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

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

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

  • @irfanfauzi8704
    @irfanfauzi8704 10 месяцев назад +8

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

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

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

  • @nadavrot
    @nadavrot Год назад +12

    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 Год назад +4

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

  • @waterbreak
    @waterbreak Год назад +3

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

  • @blazeogl7097
    @blazeogl7097 5 месяцев назад +1

    Thanks man, 3 months ago I started learning expo, and I wanted to make routes, I suffered so much because of that, I was obligated to type routes as any...and now I know how to fix it❤

  • @naraksama3903
    @naraksama3903 Год назад +3

    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 Год назад +1

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

    • @naraksama3903
      @naraksama3903 Год назад +1

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

  • @yoni532s9M5w
    @yoni532s9M5w Год назад +2

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

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

    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 Год назад

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

  • @rutabega306
    @rutabega306 Год назад +7

    Almost as good as 'as any'!

  • @TheGrandChieftain
    @TheGrandChieftain Год назад +1

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

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

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

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

    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.

  • @PraiseYeezus
    @PraiseYeezus Год назад +1

    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.

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

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

  • @josephsliman3395
    @josephsliman3395 Год назад +1

    I love your typescript content, thanks

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

    Godly gift of explanation.

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

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

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

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

  •  Год назад

    The best and simplest explanation of "as const"!

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

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

  • @Mujahedeen_
    @Mujahedeen_ Год назад +1

    YOU are the most underrated RUclipsr

  • @ginger-viking
    @ginger-viking Год назад

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

  • @rizzzzkyy
    @rizzzzkyy Год назад +6

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

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

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

  • @griffadev
    @griffadev Год назад +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

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

    Watched small video - huge power acquired. Thank you!

  • @ColinRichardson
    @ColinRichardson Год назад +86

    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 Год назад +4

      PS: Where is the Top hat and Monocle?

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

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

  • @williamlvea
    @williamlvea Год назад +4

    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

  • @olegsbk3562
    @olegsbk3562 Год назад +2

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

  • @user-he8qc4mr4i
    @user-he8qc4mr4i Год назад

    Very nice ticks! keep them comming sensei!

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

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

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

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

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

    Amazing! I needed this earlier today!

  • @DoorThief
    @DoorThief 7 месяцев назад

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

      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.

  • @Hadi-gd7ul
    @Hadi-gd7ul Год назад

    This is so beautiful that i want to cry.

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

    I don't get to just use typescript at work, but I sure as hell use jsdoc to the fullest in the meantime and love getting to do similar things with types. When you know for sure that you'll get auto completion and type errors, it's amazing how much less code you can end up writing. I recently set types up in such a way that I could safely turn 1000+ lines of manual references to properties on an object into just a few lines of code that auto updates, types and all.

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

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

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

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

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

    This is so awesome! Thank you!

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

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

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

    Thank you very much Mr Matt!

  • @sergey_llal6897
    @sergey_llal6897 Год назад +3

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

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

    Amazing so concise and clean.

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

    Simply a typescript magician

  • @zb2747
    @zb2747 Год назад +1

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

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

    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

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

    thank you, you are a life saver!

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

    Videos are very useful and clear, thanks

  • @shane3744
    @shane3744 Год назад +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.

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

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

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

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

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

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

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

      Check my video on enums

    • @3453wer
      @3453wer Год назад

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

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

    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

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

    Made me subscribe. Thank you very much. 👍

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

    Brilliant. Instant follow

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

    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!

  • @omanshsharma6796
    @omanshsharma6796 22 дня назад

    great video, thanks!!

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

    What linter is "I noticed that routes has been declared, but it's never used in the code." a part of? It sounds much closer to natural language than usual error messages do.

    • @mattpocockuk
      @mattpocockuk  Год назад +1

      It's the TypeScript error translator I built:
      marketplace.visualstudio.com/items?itemName=mattpocock.ts-error-translator

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

      @@mattpocockuk Oh neat

  • @Leon-xg7zj
    @Leon-xg7zj Год назад

    Awesome sharing!

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

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

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

    Finally something from youtube I will actually use

  • @matiaslauriti
    @matiaslauriti 22 дня назад

    I am assuming this video came out before native enums existed on TS, right?

  • @prashantjoshi6703
    @prashantjoshi6703 Год назад +2

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

    • @scylk
      @scylk Год назад +1

      Wondering the same lol

    • @FredoCorleone
      @FredoCorleone 8 дней назад

      That you can use strings and it doesn't bother

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

    Hi Matt, I'm wondering if this prettify option could/should be better or not:
    export type ValueOf = Prettify;
    type Prettify = {
    [K in keyof T]: T[K];
    } & {};

  • @zuperxtreme
    @zuperxtreme Год назад +3

    Would an enum work the same?

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

      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.

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

    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;
    };
    }

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

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

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

    is there a shorthand for this syntax (typeof variable)[keyof typeof variable]? just curious because it's this is going to be used a lot in the code base.

  • @LetrixAR
    @LetrixAR Год назад +2

    In this case, why not use enums?

    • @punsmith
      @punsmith Год назад +1

      Because, if you read the comments here, using Enums is bad for reasons most don't understand or are not impacted by in actuality. This hacky, non-intuitive solutions to a very basic problem is somehow superior, because... Well. It isn't. Glad this video doesn't disappoint, because Matt is such a massive tool. Simply look up his "Why you shouldn't use Enums" and waste minutes of your life watching a man glorify magic variables via transitive property instead of seeing Enums as what they are.

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

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

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

    Just wow. Thank you.

  • @omkarbhale442
    @omkarbhale442 Год назад +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 Год назад +1

      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 Год назад +3

      /* 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 Год назад

      @@programming5274 Yes!

    • @punsmith
      @punsmith Год назад +1

      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 Год назад

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

  • @shadilios
    @shadilios 7 дней назад

    you can just use an enum with string values?

  • @Alec.Vision
    @Alec.Vision Год назад

    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 🤷

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

    Great video, typescript is beautiful

  • @Daniel-the_one
    @Daniel-the_one Год назад

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

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

    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.

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

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

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

    For the first example, why not just declare an enum of the route paths and pass the enum value?

  • @mrvaibh0
    @mrvaibh0 7 месяцев назад

    I'm getting kinda imposter syndrome, please explain if we really use such tricky advanced concepts in coding, or is it okay if I'm using simple intermediate level code to get my stuff done, without engaging in fancy stuff like this. Btw, amazing video 🔥🔥!!

    • @Yogarine
      @Yogarine 7 месяцев назад +1

      Like everything: It really depends. If you’re not a library developer but a consumer of libraries, and you’re able to develop comfortably without leaving much bugs in the code then you’re good.
      If you _do_ often encounter bugs _OR_ if you want to continue growing as a programmer (which I assume is what you’d want) it’s wise to learn these concepts so you’re prepared in the less common cases where you run into them, or so you have a broader background to make better decisions.

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

    this video is amazing!

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

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

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

    Question here. What's the difference between using "as const" and using "Readonly" utility type????????

    • @mattpocockuk
      @mattpocockuk  Год назад +1

      With Readonly, you need to pass it a type. 'as const' operates on the value itself, so you can skip that step.

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

      @@mattpocockuk oh so they serves the same purpose that is to make something immutable, but in a different way

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

    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.

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

    That's brilliant!

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

    What's the different between this and using Enums?

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

    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 Год назад +4

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

    • @onça_pintuda999
      @onça_pintuda999 Год назад +2

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

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

    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

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

    Mind blowing 🤯

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

    I guess your example is similiar to the usage of enum (?). are there any other example besides that?

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

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

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

    Matt the goat!