Тёмный

as const: the most underrated TypeScript feature 

Matt Pocock
Подписаться 105 тыс.
Просмотров 120 тыс.
50% 1

Наука

Опубликовано:

 

29 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 320   
@TechnologicNick
@TechnologicNick Год назад
You can also use `as const` on individual value literals or use it on template string literals to get all possible strings.
@ElektrykFlaaj
@ElektrykFlaaj Год назад
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 11 месяцев назад
The template literal trick is mind blowing!
@DulithMutucumarana
@DulithMutucumarana Год назад
Awesome! Thanks! works on arrays as well: const abc = ['a', 'b', 'c'] as const; type ABC = typeof abc[number];
@rizkyagungprasetyo8293
@rizkyagungprasetyo8293 Год назад
Sometimes I utilize this tool to manage database names, collections, roles, etc., enabling me to infer values instead of strings :).
@williamlvea
@williamlvea Год назад
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
@christopheradolphe
@christopheradolphe 6 месяцев назад
Awesome tip here. Thank you @mattpocockuk for sharing this.
@somewonderfulguy
@somewonderfulguy Год назад
Watched small video - huge power acquired. Thank you!
@lambgoat2421
@lambgoat2421 8 месяцев назад
Finally something from youtube I will actually use
@Leon-xg7zj
@Leon-xg7zj Год назад
Awesome sharing!
@micelumail5829
@micelumail5829 Год назад
4:05 me knowing new ts magic
@VolodymyrEisenhorn
@VolodymyrEisenhorn Год назад
Just wow. Thank you.
@lalumierehuguenote
@lalumierehuguenote Год назад
Oh cool! I knew it for array to union, but not for object to union. Thanks!
@aamiramin6112
@aamiramin6112 Год назад
Amazing so concise and clean.
@brad8961
@brad8961 Год назад
Videos are very useful and clear, thanks
@mrvaibh0
@mrvaibh0 3 месяца назад
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 2 месяца назад
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.
@thisberandom
@thisberandom Год назад
I prefer `as any` but to each their own
@vrtech473
@vrtech473 Год назад
never knew this 😂😂😂😂 GOAT🎉🎉
@renegadeace1735
@renegadeace1735 11 месяцев назад
'as const' is also nice cause it saves you from having to do Object.freeze over and over.
@anasalhariri5474
@anasalhariri5474 9 месяцев назад
Good to know thanks for sharing :) Like and new Sub
@DaxSudo
@DaxSudo Год назад
as const is poggersa
@4w0ken
@4w0ken Год назад
this i cool and all. but its actually just a workaround for an anti pattern., in the example case u give, why are u not using an enum type on routes, if fixed values are used ?
@mattpocockuk
@mattpocockuk Год назад
Check out my video on enums
@4w0ken
@4w0ken Год назад
@@mattpocockuk instead of cloutserve ur enum video, just answer one of the 5k comments pointing out enums maybe ?
@mattpocockuk
@mattpocockuk Год назад
@@4w0ken I made an 8 minute video explaining my thoughts! That's a far better resource than a random buried comment.
@4w0ken
@4w0ken Год назад
@@mattpocockuk yeah fair
@walid_mou
@walid_mou Год назад
why don't use an Enum instead?
@reprC
@reprC Год назад
Enums are considered harmful. Matt has another video on the topic, but in short, there are a bunch of design flaws that can cause some unexpected issues at runtime without raising an error when type-checking. They’ve been improved a bit in 5.0, but still have some sneaky footguns
@4w0ken
@4w0ken Год назад
things that never happen irl. i never had any production code crash on me because of an enum. give me a break. @@reprC
@ianliu88
@ianliu88 Год назад
This looks like a very complicated way of implementing Enums in other languages 😂
@ColinRichardson
@ColinRichardson Год назад
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 Год назад
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 🎩
@weirdwordcombo
@weirdwordcombo Год назад
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.
@apina2
@apina2 Год назад
"const as const" sounds really smart and not ridiculous at all
@zuma206
@zuma206 4 месяца назад
It makes perfect sense within the typescript syntax, and it's relationship with javascript syntax
@rutabega306
@rutabega306 Год назад
Almost as good as 'as any'!
@leotravel85
@leotravel85 Год назад
You can also use 'satisfies' with 'as const' to constraint the object typings, like 'as const satisfies Record', its super neat
@Ma1ne2
@Ma1ne2 Год назад
Damn I needed this so many times and didn't know about it, thanks for sharing.
@willshadow
@willshadow Год назад
holy crap I needed this, tysm
@mananabanana
@mananabanana Год назад
"as const or how to implement a real enum in typescript" 😂
@irfanfauzi8704
@irfanfauzi8704 6 месяцев назад
It's ridiculous that I can't expect const as constant value. Love your vids
@wiktorchojnacki9746
@wiktorchojnacki9746 5 месяцев назад
You can, you just need to know what is constant about your value.
@goncaloflorencio6529
@goncaloflorencio6529 Год назад
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.
@Cahnisama
@Cahnisama Год назад
Great... now I have to clean my walls.... you HAD to blow my mind didn't you Matt? sigh... Feedback: at 5:20, you video recommendation thumbnail is covering the code you are still explaining, maybe make an outro?
@nadavrot
@nadavrot Год назад
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.
@omkarbhale442
@omkarbhale442 Год назад
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 Год назад
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 Год назад
/* 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 Год назад
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 9 месяцев назад
@@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
@Luxcium
@Luxcium Год назад
The most underrated in TypeScript is *YOU* haha just kidding you can get tell you are respected by the way everyone else are referring to the wizard 🎉🎉🎉🎉
@faez322
@faez322 Год назад
Pease add typescript playground link under your video. Thanks a lot!
@moneyfr
@moneyfr Год назад
You didn't talk about: "as const satisfies Record "
@onça_pintuda999
@onça_pintuda999 Год назад
I started using a lot of "as const satisfies typeX", I'm creating a lib and it's helping me a lot
@sergey_llal6897
@sergey_llal6897 Год назад
Can we use enum for store routes and avoid create additional types?
@olegsbk3562
@olegsbk3562 Год назад
What do you prefer “as const” or enum in cases like in video?
@zuperxtreme
@zuperxtreme Год назад
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.
@LC12345
@LC12345 Год назад
“const x as const” just feels weird to write 😂
@LetrixAR
@LetrixAR Год назад
In this case, why not use enums?
@punsmith
@punsmith Год назад
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.
@prashantjoshi6703
@prashantjoshi6703 Год назад
But what benefit it adds in comparison to string enums?🥺
@scylk
@scylk Год назад
Wondering the same lol
@smithrockford-dv1nb
@smithrockford-dv1nb Год назад
... or just use enums ...
@deniyii
@deniyii Год назад
Guess how many downvotes you have on this
@MdAdil-hl8uv
@MdAdil-hl8uv Месяц назад
type Values = T[keyof T]; const routes = { home: '/', admin: '/admin', users: '/users' } as const; type Route = Values; // Route = "/" | "/admin" | "/users"
@kmylodarkstar2253
@kmylodarkstar2253 2 месяца назад
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]; } & {};
@blazeogl7097
@blazeogl7097 Месяц назад
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❤
@omarkraidie
@omarkraidie Год назад
const obj = { username: 'abc', password: 'dce', email: 'fgh', } as const; let a: (typeof obj)[keyof typeof obj]; // Value of an object let b: Exclude; // Exclude a value from an object let c: keyof typeof obj; // Keys of an object let d: Exclude; // Exclude a key from an object
@zerosandones7547
@zerosandones7547 2 месяца назад
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.
@baka_baca
@baka_baca 2 месяца назад
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.
@dabbopabblo
@dabbopabblo Год назад
God I hate typescript. If JavaScript wasn't so flawed typescript would be a 1000X simpler
@renatodex
@renatodex 8 месяцев назад
Very useful! But what a terrible syntax 😮 Someone needs to revamp typed Javascript ASAP
@Shogoeu
@Shogoeu 4 месяца назад
Right at the end of this video, I got a suggested video "Don't use const!"
@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 🤷
@spirobel2.0
@spirobel2.0 5 месяцев назад
yeah and now pass this back into the library so the link maker function can be part of the library. And make it so the handlers and routes can be defined in one spot so we have a single source of truth. not possible, because it is a circle. I just want typescript for the autocomplete, but getting more extreme about it does not solve the issues I try to solve. maybe a custom vs code plugin / language server will do better than going deeper into this maze. There is value in typescript. But you have to know its limitations. otherwise you get stuck in a maze and forget that its original purpose was to make you more productive so you can deliver something for your users.
@danielratiu4318
@danielratiu4318 9 месяцев назад
How about routes with matching variables like '/users/:id' that match /users/3 ?
@mster50
@mster50 9 месяцев назад
Homie. Not the greatest example. Exactly the situation to utilize an enum. Flat key collection of string literals? Enum. No type gymnastics.
@lorenzorev
@lorenzorev 7 месяцев назад
Normally I would an enum in this case like "enum routes" and avoid declaring the type. What do you think?
@Zufarabyan
@Zufarabyan 4 месяца назад
I guess your example is similiar to the usage of enum (?). are there any other example besides that?
@PapitaPure
@PapitaPure 5 месяцев назад
You just saved me wtf. I was looking for a solution like this yesterday
@waterbreak
@waterbreak Год назад
After watching half of the video, I found an immediate use case in my TS project I'm working on. Great video!
@shatzofhudson
@shatzofhudson 4 месяца назад
you could also just not use typescript.....significantly easier
@mbenlahrech
@mbenlahrech 9 месяцев назад
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
@devinlauderdale9635
@devinlauderdale9635 4 месяца назад
For the first example, why not just declare an enum of the route paths and pass the enum value?
@Tony_Ryders
@Tony_Ryders 10 месяцев назад
I don’t understand the reason for all this. In such situations, you use enums which can also be used as expected interfaces within your function arguments.
@furkan7013
@furkan7013 Год назад
Anybody knows that translation plugin for error messages ?
@kmylodarkstar2253
@kmylodarkstar2253 2 месяца назад
export type ValueOf = T[keyof T];
@AlfredLotsu
@AlfredLotsu Год назад
I now understand Rich Harris. We are packing up and moving to Jsdoc
@123456crapface
@123456crapface 7 месяцев назад
oh my god typescript is awful sometimes (usually anytime i have to do something new with types)
@ThanHtutZaw3
@ThanHtutZaw3 8 месяцев назад
How can I type safe for api end point url for fetch ? Some of them will need query or other will need only body .
@yega3k
@yega3k Год назад
I get that this is how it works but specifying "const" twice just seems a bit weird to me. Why was it structured this way?
@MrJloa
@MrJloa 28 дней назад
Always use as const instead of enums. Enums are wierd in ts.
@spencereaston8292
@spencereaston8292 Год назад
And this is because, I am assuming from the pop-up, enums should not be used?
@REPOORTEHT
@REPOORTEHT Год назад
This video is pure gold, but const something as const; is still too ridiculous to read.
@properwaffles
@properwaffles Год назад
Just when I think I’m getting better with TypeScript…
@matthewbridges3147
@matthewbridges3147 Год назад
I mean it's nice, but let's not pretend that Route type signature isn't horrific
@RevHardt
@RevHardt Год назад
Can’t wait for languages to treat everything as const by default
@melvins126
@melvins126 Год назад
Made me subscribe. Thank you very much. 👍
@CFXTBogard
@CFXTBogard Год назад
by the way, the audio improved A LOT.
@mamai_eth
@mamai_eth 8 месяцев назад
Typescript ingorantee here, why is this prefered over enum?
@NoobPilot831
@NoobPilot831 8 месяцев назад
In my opinion this is just an example of where enums should be used.
@anj000
@anj000 Год назад
It is really ridiculous that we are used to something like const name = { ... } as const; If there was a new language that would propose something like this it would be laugh at till the end of times, and yet here we are, we all are using language like this. But aside from that you could do a helper type like this: type ValueOf = T[keyof T];
@nurihodges
@nurihodges Год назад
lol, “as const” is the most underrated feature, proceeds to show other features
@griffadev
@griffadev Год назад
Nice video! Heads up on this format on mobile because there's no RU-vid outro, the "suggested video" card appeared whilst you were still coding and blocked the code in video
@jpgarcia90
@jpgarcia90 9 месяцев назад
What's the different between this and using Enums?
@DoorThief
@DoorThief 3 месяца назад
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 3 месяца назад
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.
@jspesh
@jspesh 7 месяцев назад
As a C# developer, wtf
@TheGrandChieftain
@TheGrandChieftain Год назад
Was using an enum for a radio group in Zod and discovered this. Never went through the trouble of understanding it, though. Thanks 👍🏿
@patsy02
@patsy02 Год назад
RU-vid's suggested video box is hiding the end of your video
@Vampirat3
@Vampirat3 Год назад
The resaon for this is you forgot how to use escape characters....
@ra2enjoyer708
@ra2enjoyer708 Год назад
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 Год назад
You can use ts-reset to fix that Array.includes issue.
@ilearncode7365
@ilearncode7365 Год назад
Theres gotta be a better than this “keyof typeof typeof keyof” shit
@tntg5
@tntg5 5 месяцев назад
You can enum for routes and save yourself some time
@tronixmobile
@tronixmobile Год назад
Values are no Types. My head hurts 😮.
@vovasava3498
@vovasava3498 11 месяцев назад
object as const is what Enums were supposed to be
@yoni532s9M5w
@yoni532s9M5w Год назад
That's worthy of a medium article mate. Very nice solution to a very popular recurring problem
@thelaitas
@thelaitas Год назад
2nd most underrated has to be discriminated unions
@studiowebselect
@studiowebselect Год назад
Instead of Enums I always do this way.
@echobucket
@echobucket Год назад
Why not just use a union of strings for this?
@RockTheCage55
@RockTheCage55 Год назад
Excellent....pretty cool. Thanks....
@leesasuki
@leesasuki 8 месяцев назад
thank you, you are a life saver!
Далее
Generics: The most intimidating TypeScript feature
18:19
Enums considered harmful
9:23
Просмотров 206 тыс.
FATAL CHASE 😳 😳
00:19
Просмотров 1,4 млн
▼ КАПИТАН НАШЁЛ НЕФТЬ В 🍑
33:40
Просмотров 311 тыс.
Real 10x Programmers Are SLOW To Write Code
14:51
Просмотров 48 тыс.
Breaking down React "head" drama
19:55
Просмотров 48 тыс.
Why use Type and not Interface in TypeScript
14:12
Просмотров 207 тыс.
Will Deno 2.0 Replace Node.js?
12:35
Просмотров 58 тыс.
Infer is easier than you think
13:38
Просмотров 90 тыс.
Let's Fix The Fatal Flaw in TypeScript's Union Types!
13:45
The TSConfig Cheat Sheet
5:36
Просмотров 36 тыс.
Умный обзор умного iPhone 16 / 16 Pro
21:21
Круче iPhone
0:29
Просмотров 13 тыс.
КУПИЛ IPHONE 15 PRO ЗА 87000 РУБЛЕЙ!
27:33