as const: the most underrated TypeScript feature

Ғылым және технология

'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

Пікірлер: 306

  • @apina2
    @apina29 ай бұрын

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

  • @zuma206

    @zuma206

    17 күн бұрын

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

  • @TechnologicNick
    @TechnologicNick9 ай бұрын

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

  • @ElektrykFlaaj

    @ElektrykFlaaj

    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

    7 ай бұрын

    The template literal trick is mind blowing!

  • @weirdwordcombo
    @weirdwordcombo9 ай бұрын

    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
    @leotravel859 ай бұрын

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

  • @Ma1ne2

    @Ma1ne2

    9 ай бұрын

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

  • @willshadow

    @willshadow

    9 ай бұрын

    holy crap I needed this, tysm

  • @goncaloflorencio6529
    @goncaloflorencio65299 ай бұрын

    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.

  • @nadavrot
    @nadavrot9 ай бұрын

    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.

  • @uicornerwithJ
    @uicornerwithJ8 ай бұрын

    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.

  • @Gustavewpm
    @Gustavewpm2 ай бұрын

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

  • @DulithMutucumarana
    @DulithMutucumarana9 ай бұрын

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

  • @waterbreak
    @waterbreak9 ай бұрын

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

  • @josephsliman3395
    @josephsliman33959 ай бұрын

    I love your typescript content, thanks

  • @ColinRichardson
    @ColinRichardson9 ай бұрын

    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

    9 ай бұрын

    PS: Where is the Top hat and Monocle?

  • @SimGunther

    @SimGunther

    9 ай бұрын

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

  • @AlessioMichelini
    @AlessioMichelini9 ай бұрын

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

  • @mattinpjs
    @mattinpjs9 ай бұрын

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

  • @hatchibomb
    @hatchibomb9 ай бұрын

    Amazing! I needed this earlier today!

  • @adi96adi
    @adi96adi4 ай бұрын

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

  • @JDalmasca
    @JDalmasca9 ай бұрын

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

  • @nixoncode
    @nixoncode9 ай бұрын

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

  • @naraksama3903
    @naraksama39039 ай бұрын

    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

    9 ай бұрын

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

  • @naraksama3903

    @naraksama3903

    9 ай бұрын

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

  • @TheGrandChieftain
    @TheGrandChieftain9 ай бұрын

    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-xt1ry9 ай бұрын

    Very nice ticks! keep them comming sensei!

  • @Nabulio85
    @Nabulio859 ай бұрын

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

  • @brad8961
    @brad89619 ай бұрын

    Videos are very useful and clear, thanks

  • @rizkyagungprasetyo8293
    @rizkyagungprasetyo82939 ай бұрын

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

  • @grandpowr
    @grandpowr9 ай бұрын

    Thank you very much Mr Matt!

  • 9 ай бұрын

    The best and simplest explanation of "as const"!

  • @giodefreitas
    @giodefreitas9 ай бұрын

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

  • @williamlvea
    @williamlvea9 ай бұрын

    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

  • @griffadev
    @griffadev9 ай бұрын

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

  • @somewonderfulguy
    @somewonderfulguy8 ай бұрын

    Watched small video - huge power acquired. Thank you!

  • @irfanfauzi8704
    @irfanfauzi8704Ай бұрын

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

  • @wiktorchojnacki9746

    @wiktorchojnacki9746

    Ай бұрын

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

  • @christopheradolphe
    @christopheradolphe2 ай бұрын

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

  • @melvins126
    @melvins1269 ай бұрын

    Made me subscribe. Thank you very much. 👍

  • @aamiramin6112
    @aamiramin61129 ай бұрын

    Amazing so concise and clean.

  • @yoni532s9M5w
    @yoni532s9M5w9 ай бұрын

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

  • @Rivernile345
    @Rivernile3459 ай бұрын

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

  • @leesasuki
    @leesasuki4 ай бұрын

    thank you, you are a life saver!

  • @PapitaPure
    @PapitaPure28 күн бұрын

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

  • @ginger-viking
    @ginger-viking9 ай бұрын

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

  • @zb2747
    @zb27479 ай бұрын

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

  • @AudaiAlFandi
    @AudaiAlFandi9 ай бұрын

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

  • @olegsbk3562
    @olegsbk35629 ай бұрын

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

  • @Leon-xg7zj
    @Leon-xg7zj9 ай бұрын

    Awesome sharing!

  • @stephanfitzpatrick1769
    @stephanfitzpatrick17694 ай бұрын

    Brilliant. Instant follow

  • @aram5642
    @aram56428 ай бұрын

    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!

  • @PraiseYeezus
    @PraiseYeezus9 ай бұрын

    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-gd7ul9 ай бұрын

    This is so beautiful that i want to cry.

  • @AbWischBar
    @AbWischBar9 ай бұрын

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

  • @robertmengual8357
    @robertmengual83579 ай бұрын

    Great video, typescript is beautiful

  • @VolodymyrEisenhorn
    @VolodymyrEisenhorn9 ай бұрын

    Just wow. Thank you.

  • @maxwebstudio
    @maxwebstudio9 ай бұрын

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

  • @Dmitri_Ivanovich
    @Dmitri_Ivanovich9 ай бұрын

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

  • @dawid_dahl
    @dawid_dahl9 ай бұрын

    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.

  • @mattpocockuk

    @mattpocockuk

    9 ай бұрын

    It is!

  • @sc76399
    @sc763999 ай бұрын

    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

  • @MightyKingKala
    @MightyKingKala9 ай бұрын

    this video is amazing!

  • @alexeypetrov8543
    @alexeypetrov85439 ай бұрын

    That's brilliant!

  • @skandertebourbi357
    @skandertebourbi3579 ай бұрын

    Simply a typescript magician

  • @mbenlahrech
    @mbenlahrech5 ай бұрын

    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

  • @Mujahedeen_
    @Mujahedeen_9 ай бұрын

    YOU are the most underrated KZreadr

  • @wattsfield1889
    @wattsfield18899 ай бұрын

    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

  • @RockTheCage55
    @RockTheCage559 ай бұрын

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

  • @sergey_llal6897
    @sergey_llal68978 ай бұрын

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

  • @thekaasim
    @thekaasim9 ай бұрын

    helpful video. thanks.

  • @maxwebstudio
    @maxwebstudio9 ай бұрын

    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 ?

  • @user-hk6ns2eg1w
    @user-hk6ns2eg1w5 ай бұрын

    Nice!! thanks

  • @rockNbrain
    @rockNbrain9 ай бұрын

    Nice job 🎉

  • @osamanajjar1934
    @osamanajjar19349 ай бұрын

    Matt the goat!

  • @lalumierehuguenote
    @lalumierehuguenote9 ай бұрын

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

  • @omkarbhale442
    @omkarbhale4429 ай бұрын

    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

    9 ай бұрын

    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

    9 ай бұрын

    /* 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

    9 ай бұрын

    @@programming5274 Yes!

  • @punsmith

    @punsmith

    9 ай бұрын

    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

    5 ай бұрын

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

  • @lambgoat2421
    @lambgoat24214 ай бұрын

    Finally something from youtube I will actually use

  • @micelumail5829
    @micelumail58299 ай бұрын

    4:05 me knowing new ts magic

  • @ThanHtutZaw3
    @ThanHtutZaw34 ай бұрын

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

  • @Alec.Vision
    @Alec.Vision9 ай бұрын

    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 🤷

  • @StephenRayner
    @StephenRayner9 ай бұрын

    Beautiful

  • @danielratiu4318
    @danielratiu43185 ай бұрын

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

  • @barneylaurance1865
    @barneylaurance18659 ай бұрын

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

  • @Orenrs
    @Orenrs9 ай бұрын

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

  • @mattpocockuk

    @mattpocockuk

    9 ай бұрын

    Check my video on enums

  • @3453wer

    @3453wer

    5 ай бұрын

    @@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
    @rhodler21 күн бұрын

    Merci !

  • @mananabanana
    @mananabanana9 ай бұрын

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

  • @zuperxtreme
    @zuperxtreme9 ай бұрын

    Would an enum work the same?

  • @punsmith

    @punsmith

    9 ай бұрын

    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.

  • @alexking7684
    @alexking76849 ай бұрын

    Fenomenal! 🎉

  • @segen8324
    @segen83249 ай бұрын

    this is beautiful

  • @furkan7013
    @furkan70139 ай бұрын

    Anybody knows that translation plugin for error messages ?

  • @prashantjoshi6703
    @prashantjoshi67039 ай бұрын

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

  • @scylk

    @scylk

    9 ай бұрын

    Wondering the same lol

  • @ra2enjoyer708
    @ra2enjoyer7089 ай бұрын

    Another trick is `as const` objects somewhat work with built-in methods while almost not losing all type info: ```typescript const ROUTES = { home: "/", admin: "/admin", users: "/users" } as const; // sadly not a tuple of literals, merely an array of literal type union const routeValues = Object.values(ROUTES).map((value) => value); export type IRoute = (typeof routeValues)[number]; export function validateRouteValue(inputValue: unknown): inputValue is IRoute { // have to coerse type there because typescript is iffy with `Array.includes()` // when it's array of string literals return routeValues.includes(inputValue as IRoute); } export function doSomethingFromValue(inputValue: IRoute): void { switch (inputValue) { case "/": case "/admin": case "/users": { break; } default: { throw new Error(`Invalid value "${inputValue satisfies never}"`) } } } ``` Achieves the same result but you also get a validation function which acts as a type predicate. The `doSomethingFromValue()` also shows how literal type unions can be paired with `satisfies` keyword to achieve exhaustive switch cases.

  • @mattpocockuk

    @mattpocockuk

    9 ай бұрын

    You can use ts-reset to fix that Array.includes issue.

  • @shane3744
    @shane37449 ай бұрын

    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.

  • @vrtech473
    @vrtech4739 ай бұрын

    never knew this 😂😂😂😂 GOAT🎉🎉

  • @anasalhariri5474
    @anasalhariri54745 ай бұрын

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

  • @Jiftoo
    @Jiftoo9 ай бұрын

    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

    9 ай бұрын

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

  • @Jiftoo

    @Jiftoo

    9 ай бұрын

    @@mattpocockuk Oh neat

  • @NuncNuncNuncNunc
    @NuncNuncNuncNunc9 ай бұрын

    Is there an advantage over creating an enum if you just have a flat list of constant keys?

  • @LeighBriody

    @LeighBriody

    9 ай бұрын

    My thoughts exactly , is this not just enums?

  • @casdf7

    @casdf7

    9 ай бұрын

    Yes multiple: Enums only fake being read-only while actually being changable. Enums create js code, while types won't (and a weird one too). Enums also are not as compatible with the typing algebra so at some point you will break it (e.g. a function takes in a parameter that is a subset of two enums)

  • @NuncNuncNuncNunc

    @NuncNuncNuncNunc

    5 ай бұрын

    @@casdf7 Is the last point correct? I've never had a function take a subset of two enums as a single parameter (don't think I ever will) but can't that be solved using typeof and type unions? If you meant a subset of a single enum which makes more sense, will something like `type Barbaz = typeof Foo.bar | typeof Foo.baz;` work?

  • @user-qk2nl8lf9y
    @user-qk2nl8lf9y9 ай бұрын

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

  • @mattpocockuk

    @mattpocockuk

    9 ай бұрын

    www.totaltypescript.com/vscode-extension

  • @user-qk2nl8lf9y

    @user-qk2nl8lf9y

    9 ай бұрын

    @@mattpocockuk Thanks so much!

  • @kelvindecosta5350
    @kelvindecosta53509 ай бұрын

    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

    9 ай бұрын

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

  • @lorenzorev
    @lorenzorev3 ай бұрын

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

  • @jpgarcia90
    @jpgarcia905 ай бұрын

    What's the different between this and using Enums?

  • @AlfredLotsu
    @AlfredLotsu8 ай бұрын

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

  • @spencereaston8292
    @spencereaston82929 ай бұрын

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

  • @josemfcheo
    @josemfcheo4 ай бұрын

    this is awesome

  • @moneyfr
    @moneyfr9 ай бұрын

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

  • @joaofrancisco5781

    @joaofrancisco5781

    9 ай бұрын

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

  • @latituddev7884
    @latituddev78849 ай бұрын

    what is that extension that translates ts errors i need it

  • @zapxcero

    @zapxcero

    3 ай бұрын

    probably Total Typescript

  • @devinlauderdale9635
    @devinlauderdale963514 күн бұрын

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

Келесі