To me the title of this video is “how to create and consume decorators: a blazing fast tutorial” I finally got a clear explanation of decorators. Thanks Matt.
@@akatsukilevi You will notice a huge difference if you're coming from Java, but even in general its a solid language thats well thought out and modern. Same as TS and JS, you can mix Java and Kotlin so you can adapt it incrementally. Android - one of the biggest mobile platform, ditched Java and switched to supporting Kotlin as its recommended language and thats just a testament to Kotlin's qualities.
Over the last year or so, I've been coding in typescript for the first time professionally (I've been a JavaScript developer since Netscape Navigator Gold back in high school), and I feel like I am just now getting to the level where I can notice the limitations of the language and appreciate these improvements. This is a very helpful channel in putting these enhancements into some context, thank you for this valuable content :)
I use decorators a lot already, but I don't know any TS dev that uses classes. I feel like they really should get decorators working on regular functions
A decorator for a regular function is just a wrapper function ... function log(fn) { return (...args) => { let result = fn(...args) console.log({ args }) console.log({ result }) return result; } } log(getUserById)(12)
don't need decorators if doing functional programming anyway. It's much easier to have a "function that returns a function", as easy as const getUserWithLogging = withLogging(getUser); No need of unnecessary abstractions and complications :)
Decorators seem like a very complicated way to do with classes something that is easy to do with regular functions using composition. Am I missing something?
@@avi3681 exactly! an unnecessary complication that adds no value over composition except that you’re making the composition less explicit and obvious. pretty much the ethos of all OOP, “hide things away behind so many layers that it’s all eventually a garbled mess where asking for a monkey gets u a forest”
@@avi3681 I use decorators on my web api controller lib, TSOA, to easily manage a bunch of info related to the routes, like @Get(x), @Public(), @AdminAuth(x), @ResponseSchema(x), @Validate(x), etc. There's a lot of info in there. If you were to do this with regular functions and composition, it would potentially not be as readable. But if you keep it clean, maybe.
Great summary, Matt. Really, REALLY looking forward to your video on properly typing decorators! The beta TS release article was helpful, but left a bit to be desired. Thanks for all the awesome content ❤
5:30 this is epic, i can use this for caching the results of the calls or to put stuff in queue on async calls etc many things before that you had to wrapper the thing, like getPost = log((id: string) => { ... }) which becomes ugly quickly
I'm a relatively new Typescript dev, but these changes particularly to the function generics look really cool! As your example used terms Routes and Router, it immediately springs to mind how much easier a dev would be able to write links in an app as the actual urls could be type-hinted to them!
Hey matt Thanks for all you're sharing. (waiting for the next episode of TS challenge though :) ) You can have decorators for functions as well. I think you can create a memoize hook but no linter supports it so no one will tell you when for example you forget some dependency. It's been lovely to see you, too :)
Can't wait for the video on decorators. Struggle with typing them properly. Especially I have issues with inability of typescript to infer the result of a decorator or at least error on me if there is a mismatch. Or it seems I might just be missing something in understanding.
Love it when standards prevail. Can't wait to finally start using decorators. That said, don't they also work for functional components? Or just for class methods and classes? Because in a React functional component, I'd probably want to use decorators on even anonymous functions.
@@mattpocockuk from that release: "Decorators can be used on more than just methods! They can be used on properties/fields, getters, setters, and auto-accessors. Even classes themselves can be decorated for things like subclassing and registration."
2:04 i wonder if i can use this with the template syntax like html`${foo}` function html(htmls: H, values: ValuesFromHtmls) so i get the type ['', ''] instead of readonly string[]
I think the move to functional programming and ditching classes is probably a good direction and is probably not going to be reversed. Especially since the functionality you showed with decorators have been around for a while (even though it was technically "experimental").
people dont realize how powerful classes are in my opinion best thing about classes is the `instanceof` keyword which lets you check "types" in runtime which is a super power if you ask me it has no alternative
I was looking for some way of inferring const types last week. would've saved me a lot of hassle with my custom list component for trpc that accepts any router with specific input declaration. I kept running into query key mismatch since trpc query keys are constants, couldn't assign "[string, {page:number....}]" to "[company.all, {page:number...}]". I'm pretty sure const key inference would have fixed that. I managed to slap together some magic to make it pass either way, and I doubt it would be useful to have a specific key in this particular scenario, but I can see the possibilities aplenty! bummed that decorators are only for classes. Still waiting for a language that has decorators as easy to use as python for plain functions.
This is a cool concept but... It's also a good way to obfuscate a lot of things and to loose a lot of readability in your code. Really not my prefered feature ^^
Hm. Interesting with decorators being able to log the name of a function. Obviously it's necessary but I was recently searching for a way to get the name of a general function and there was almost no way that wasn't terribly hacky. At least there is now for methods with decorators.
I mean, the decorators were there for a long time now I don't see why it should change the way people write code nowadays. I personally love using decorators and writing oop. The only thing that bothers me is how the new syntax will be introduced. Will it live together with the current one for some time or it will be a massive breaking change?
Frameworks that rely on the old decorator syntax will have to migrate, that's for sure. But this is coming from JS itself, not TS. The experimental decorator syntax was basically added to TS after pressure from Google - because Google came super-close to creating their own version of TS JUST so they could use decorators in Angular. But after TS added support for them, TS saw huge adoption as part of angular. But now folks have realised the problems with the experimental syntax, and we've reached a new, better proposal which is going to be part of the JS language natively. The experimental syntax lost, so it needs to be phased out.
@@mattpocockuk but as mentionned in a previous comment, there are still only available for classes, class methods and I assume class method properties... So still need to do function wrapper for anything else... That's uggly option in my opinion compare to decorators
ooo those decorators are REALLY interesting! They kinda remind me of some simple macros in Rust, and I could *absolutely* see them being used in tandem with testing frameworks. Is this a fair comparison? :o
Spring/Java dev here - I hate how it’s called “decorator” in my world it’s been a thing for quite some time and it’s just called annotated. I literally did the same logic to simplify the logs in have Java on a rest service 3 years ago! Haha how funny!
I still don't really like that you have to import an enum to be able to use it. I don't like that I can't pass LogLevel2.DEBUG to LogLevel. I like my typings structural, not nominal. Also, const enums are still terrifying.
Auto complete and fixed routes defining hell yeah!! I was debugging a invalid route for hours. Thankfully it will not happen again with this trick in typescript 5.0 👌
I think decorators aren't really giving us anything of value because you could just as easily turn that method into a function and then you can create a function that takes callbacks and does something similar... with the bonus that wrapping functions in functions is actually statically analyzable so you can actually make typesafe wrapper functions that, say, only accept functions with a string as their first argument or something.
not gonna lie, i am learning javascript now and seeing all this typescript makes my brain hurt!! all these types i am used to seeing in java but i cant quite understand the syntax when it comes to TS. Are there any free resources you recommend or have used yourself to learn TS??
Actually, this is bad (1:11). Why is one able to implicitly cast int to an enum type? That demolishes the whole idea about enum. One was already able to do this (3:03), and that was "T extends string". Pretty simple and also limits a possible type, down to a string. What did 'const' change, I wonder? 🧐
I was also hopeful for a pure function keyword. A keyword that you can’t modify parent scope. Which I know banning closures & higher order functions is nearly impossible. But even a limited scope way and expand later would be great
AFAIK the ecmascript decorators are less powerful than the experimental decorators we've all been using so far. i heard things like reflect-metadata library dont work with the official decorators or something like that
I'm fine with leaving classes in the dust. All those decorators do is add a ton of confusing indirection. I get _why_ they exist, but I never liked it C#, and I really don't like it in TS.
To be honest, I have mixed feelings about decorators. I understand the type of problem they're intended to solve, it just feels it needs some finessing, not least of which is to cleanup those anys. At least they look a lot easier to do local decorator functions. One of the problems I have with decorators in Java is how they're everywhere. This strongly suggests a language feature taken far far past their original envisaged use which usually means they're filling a need the language doesn't otherwise meet.
Yep! You can clean up the any's, I'll show how in a future video. They're actually perfectly type-safe, I can't find any way to break them at the moment.
I'm not sure that decorators will revive React class components and to be honest, I hope they don't. As far as I know React team mentioned in the past that classes are problematic in JS since they are just syntactic sugar and they cause problems with bundling and minifying. I don't see React classes coming back and I hope that React team does deprecate them in the future. Regarding decorators in general, I don't do much OOP really so I don't write classes, but they do make things tidy and more readable, that's for sure. When I had to write MobX stores, using decorators just produced way cleaner and more understandable code.
To me the title of this video is “how to create and consume decorators: a blazing fast tutorial”
I finally got a clear explanation of decorators. Thanks Matt.
TS is slowly doing to JS what Kotlin did to Java and I love every bit of it.
Everyone tells me about Kotlin, is it really this good?
@@akatsukilevi You will notice a huge difference if you're coming from Java, but even in general its a solid language thats well thought out and modern. Same as TS and JS, you can mix Java and Kotlin so you can adapt it incrementally.
Android - one of the biggest mobile platform, ditched Java and switched to supporting Kotlin as its recommended language and thats just a testament to Kotlin's qualities.
@@wlockuz4467 Huh, gotta start messing around with Kotlin
Decorators are stage 3 proposal in JavaScript, started in 2019. At this point it's not clear which one of TS or JS is catching up with the other.
Nothing?
Over the last year or so, I've been coding in typescript for the first time professionally (I've been a JavaScript developer since Netscape Navigator Gold back in high school), and I feel like I am just now getting to the level where I can notice the limitations of the language and appreciate these improvements. This is a very helpful channel in putting these enhancements into some context, thank you for this valuable content :)
const in generics is exactly what i've been missing on the lib i'm working on
It’s a game changer
It doesn't actually add any new functionality. All it does is beautify the current syntax.
@@kadensharpin2156 It does add new native functionality!
@@mattpocockuk What do you mean by native functionality?
Same here
Great video matt. You did a much better job slowing down in this one. I love it, keep it up.
I really love the const in generics and the decorators. It will open up so many new possibilities to write safer and cleaner code!
Keep posting these videos around this time ser, much appreciated.
"T const" is so geat, I can't believe I will be able to use it really soon
I really love this kind of video, not so much screen switching and I can understand you better since you are not talking too fast. more power matt!
Nice, that's great to know!
I use decorators a lot already, but I don't know any TS dev that uses classes. I feel like they really should get decorators working on regular functions
A decorator for a regular function is just a wrapper function ...
function log(fn) {
return (...args) => {
let result = fn(...args)
console.log({ args })
console.log({ result })
return result;
}
}
log(getUserById)(12)
don't need decorators if doing functional programming anyway. It's much easier to have a "function that returns a function", as easy as
const getUserWithLogging = withLogging(getUser);
No need of unnecessary abstractions and complications :)
Decorators seem like a very complicated way to do with classes something that is easy to do with regular functions using composition. Am I missing something?
@@avi3681 exactly! an unnecessary complication that adds no value over composition except that you’re making the composition less explicit and obvious. pretty much the ethos of all OOP, “hide things away behind so many layers that it’s all eventually a garbled mess where asking for a monkey gets u a forest”
@@avi3681 I use decorators on my web api controller lib, TSOA, to easily manage a bunch of info related to the routes, like @Get(x), @Public(), @AdminAuth(x), @ResponseSchema(x), @Validate(x), etc. There's a lot of info in there. If you were to do this with regular functions and composition, it would potentially not be as readable. But if you keep it clean, maybe.
Dig the enthusiasm man - you strike me as a fun engineer to work on projects with
Great summary, Matt. Really, REALLY looking forward to your video on properly typing decorators! The beta TS release article was helpful, but left a bit to be desired. Thanks for all the awesome content ❤
Amazing video! Love these short vids with current updates, keep us up-to-date more, plese!
"nah bro web dev isnt that stressful"
his hair: are you sure about that
5:30 this is epic, i can use this for caching the results of the calls
or to put stuff in queue on async calls etc many things
before that you had to wrapper the thing, like
getPost = log((id: string) => { ... })
which becomes ugly quickly
I'm a relatively new Typescript dev, but these changes particularly to the function generics look really cool!
As your example used terms Routes and Router, it immediately springs to mind how much easier a dev would be able to write links in an app as the actual urls could be type-hinted to them!
Tanstack Router already has type safe routing :)
Decorators are a really good deal. And const generics is what we could've used in our in-house but we had to seed the data and find pattern around it.
love this video TY. ohhh and please cover this in depth in your course.
For sure, will do!
Angular’s been using those decorators since 2.0. I’m interested to see what the TS 5.0 changes will do to help the framework.
They've been using the experimental decorators, which are different!
Brilliant vid on TS 5.0, well explained as always and looking forward to the "course drop" :)
Coming from Python, its decorator syntax always felt like it'd fit very nicely with JS' mostly function-first approach
Happy about decorators! Been using them heavily in our web engine and loving them
Waiting for the types for decorators video! Have struggled with that too
Hey matt
Thanks for all you're sharing. (waiting for the next episode of TS challenge though :) )
You can have decorators for functions as well. I think you can create a memoize hook but no linter supports it so no one will tell you when for example you forget some dependency.
It's been lovely to see you, too :)
Not the new decorators! They only work for classes, not for individual function calls.
Thank you Matt for your hard work!
I love classes, use them all the time. Updates to decorators is welcome, looking forwards to what comes next :)
Oh my const! Great improvement! 👏👏👏
Can't wait for the video on decorators. Struggle with typing them properly.
Especially I have issues with inability of typescript to infer the result of a decorator or at least error on me if there is a mismatch.
Or it seems I might just be missing something in understanding.
Hope Decorator pattern is gonna encourage stabilized Dependency Injection libraries.
I use NestJS which has some great DI
I love the new decorator syntax, much easier to implement, just wondering if calling log (with ()) does not have any side effects?
It would be a type error!
@@mattpocockuk thanks!
Great new features I am looking forward to. 😄
Awesome video. Look forward to using this in prod!
Adding decorators to plain function could also be neat
Love it Matt, many thanks for those brilliant video that you are serving to us... 😍😍😍
awesome the const annotations!
Holy shit, finally no more Reflect Metadata to create a simple decorator. That's a very welcome change
Reflect metadata?
@@bobobo1673 reflect-metadata to be exact, it adds (or explicitly wraps) the Reflect namespace to add additional utility stuff to create decorators
I really love the decorator part
I barely know how to use the basics, but I appreciate the improvements. I'll get there and become a "wizard" one day. :p I'll check your course.
Love it when standards prevail. Can't wait to finally start using decorators. That said, don't they also work for functional components? Or just for class methods and classes? Because in a React functional component, I'd probably want to use decorators on even anonymous functions.
Just class methods and classes AFAIK!
@@mattpocockuk Do you think their is a way to get around this?
@@mattpocockuk from that release: "Decorators can be used on more than just methods! They can be used on properties/fields, getters, setters, and auto-accessors. Even classes themselves can be decorated for things like subclassing and registration."
@@adambickford8720 Sorry, yes - I meant all aspects of classes, not just methods. Thanks for the clarification!
2:04
i wonder if i can use this with the template syntax
like html`${foo}`
function html(htmls: H, values: ValuesFromHtmls)
so i get the type ['', ''] instead of readonly string[]
Just wondering what is the type of ValuesFromHtmls, just to test it?
and the full function html?
@@ScorpioneOrzion i was checking the string literals and if they are ending with `
const generics seems like a huge game changer, I already know a couple places in the codebase I work with daily that could use it
I think the move to functional programming and ditching classes is probably a good direction and is probably not going to be reversed. Especially since the functionality you showed with decorators have been around for a while (even though it was technically "experimental").
This was brilliant, much better paced ❤
Mostly code in functions so seeing class always bring me down a little bit, but can't wait to see how typescript add spices for class!
yessss, hope decorators become better and better
Const annotations will be very awesome haha
I remember seeing someone implementing decorators by hand and thinking: if only there was a better way.
Bro you're simply amazing 😍.. keep more videos like this coming.. I will like to see some on nestjs if you can.. thanks again
Yes for decorator typing!
3:30 100% agree, that is fucking huge
We need that decorators video :)
Great video!
people dont realize how powerful classes are in my opinion
best thing about classes is the `instanceof` keyword which lets you check "types" in runtime which is a super power if you ask me
it has no alternative
people don't realize how overrated classes are, imo.
I was looking for some way of inferring const types last week. would've saved me a lot of hassle with my custom list component for trpc that accepts any router with specific input declaration.
I kept running into query key mismatch since trpc query keys are constants, couldn't assign "[string, {page:number....}]" to "[company.all, {page:number...}]". I'm pretty sure const key inference would have fixed that.
I managed to slap together some magic to make it pass either way, and I doubt it would be useful to have a specific key in this particular scenario, but I can see the possibilities aplenty!
bummed that decorators are only for classes. Still waiting for a language that has decorators as easy to use as python for plain functions.
Would be nice to see some new syntax for function decorators. Seems like currently we have to do it the old-fashioned way
I've been wondering... why can you only assign decorators to class methods? Why not regular loose/top-level functions too? (not in a class)
Please mention the relevant TS doc links in description.
first time i heard someone say "roooter". great vid btw 👍
Decorators (annotations) are absolutely huge java and fundamentally change the way you code. I'm really curious to see how this hits the TS community.
This is a cool concept but... It's also a good way to obfuscate a lot of things and to loose a lot of readability in your code. Really not my prefered feature ^^
@@RatonBroyeur true, they are good if you keep it simple. But I've seen too much decorator abuse in the wild
So you are telling that my beautiful code, wich I have improved over last month can be even shorter with decorators?
Thanks for the tip!
Thanks for the video! I'm curious what's the future of all projects that rely heavily on experimental decorators? For example Nest.js and its plugins
I imagine they'll have to migrate, but experimental decorators aren't going anywhere. So it would be great if they do migrate, but they don't have to.
I agree the const in generics is an useful feature, but worry this syntax is not very self-descriptive at all.
holy im hyped to const in generics
Matt, you should make TS certificate!
Hm. Interesting with decorators being able to log the name of a function. Obviously it's necessary but I was recently searching for a way to get the name of a general function and there was almost no way that wasn't terribly hacky. At least there is now for methods with decorators.
Please bring the video about decorators :D
看着发量就知道.绝对的专家级程序员
Why “any” and not “unknown” for decorator example?
Does const in generics solve the issue where using T for a function argument return type still allows you to specify values not on T?
No, I wouldn't characterise this as an issue to begin with.
I mean, the decorators were there for a long time now I don't see why it should change the way people write code nowadays. I personally love using decorators and writing oop. The only thing that bothers me is how the new syntax will be introduced. Will it live together with the current one for some time or it will be a massive breaking change?
Frameworks that rely on the old decorator syntax will have to migrate, that's for sure. But this is coming from JS itself, not TS.
The experimental decorator syntax was basically added to TS after pressure from Google - because Google came super-close to creating their own version of TS JUST so they could use decorators in Angular. But after TS added support for them, TS saw huge adoption as part of angular.
But now folks have realised the problems with the experimental syntax, and we've reached a new, better proposal which is going to be part of the JS language natively. The experimental syntax lost, so it needs to be phased out.
@@mattpocockuk but as mentionned in a previous comment, there are still only available for classes, class methods and I assume class method properties... So still need to do function wrapper for anything else... That's uggly option in my opinion compare to decorators
@@yoyo26-34 I imagine there's a proposal out there to add them!
Can you hover on the decorator to see what is the content of it? or can you use go to definition to the decorator code?
weren't decorators already in typescript though ?
const generic is amazing!
ooo those decorators are REALLY interesting! They kinda remind me of some simple macros in Rust, and I could *absolutely* see them being used in tandem with testing frameworks. Is this a fair comparison? :o
hey sir do you have a typescript course
Here you go!
totaltypescript.com/
@@mattpocockuk thank you sir
do new decorators modify type of decorated method accordingly to type changes they make?
No, they don't!
Spring/Java dev here - I hate how it’s called “decorator” in my world it’s been a thing for quite some time and it’s just called annotated.
I literally did the same logic to simplify the logs in have Java on a rest service 3 years ago! Haha how funny!
NestJS use a lot of decorators
Thank you explained
Decorators ❤
Why do decorators presume Classes? Can' t you decorate a regular function?
that have no purpose
got most of this but im not sure I know what a ROOTER is.
Niiiice!!
Amazing :)
Out of curiosity, why doesn't this change your opinion on enums?
I still don't really like that you have to import an enum to be able to use it. I don't like that I can't pass LogLevel2.DEBUG to LogLevel. I like my typings structural, not nominal.
Also, const enums are still terrifying.
Auto complete and fixed routes defining hell yeah!! I was debugging a invalid route for hours. Thankfully it will not happen again with this trick in typescript 5.0 👌
I think decorators aren't really giving us anything of value because you could just as easily turn that method into a function and then you can create a function that takes callbacks and does something similar... with the bonus that wrapping functions in functions is actually statically analyzable so you can actually make typesafe wrapper functions that, say, only accept functions with a string as their first argument or something.
These decorators _are_ statically analyzable! I'll do a video on getting them typesafe soon.
@@mattpocockuk that does make me more curious! The original TS only decorators weren't, right?
not gonna lie, i am learning javascript now and seeing all this typescript makes my brain hurt!! all these types i am used to seeing in java but i cant quite understand the syntax when it comes to TS. Are there any free resources you recommend or have used yourself to learn TS??
totaltypescript.com has a free beginners course!
Actually, this is bad (1:11). Why is one able to implicitly cast int to an enum type? That demolishes the whole idea about enum.
One was already able to do this (3:03), and that was "T extends string". Pretty simple and also limits a possible type, down to a string. What did 'const' change, I wonder? 🧐
can’t log be a class instead of a function within a function? need eslint rule to ban function in functions…
I was also hopeful for a pure function keyword. A keyword that you can’t modify parent scope. Which I know banning closures & higher order functions is nearly impossible. But even a limited scope way and expand later would be great
Decorators remind me of C#
enums are great :-)
AFAIK the ecmascript decorators are less powerful than the experimental decorators we've all been using so far. i heard things like reflect-metadata library dont work with the official decorators or something like that
Yes I think the pieces of the experimental decorators are spread out over a couple of ES proposals
I feel like adding decorators is a dangerous step back down the path of aspect oriented programming.
const T 🤟
I'm fine with leaving classes in the dust. All those decorators do is add a ton of confusing indirection. I get _why_ they exist, but I never liked it C#, and I really don't like it in TS.
To be honest, I have mixed feelings about decorators. I understand the type of problem they're intended to solve, it just feels it needs some finessing, not least of which is to cleanup those anys. At least they look a lot easier to do local decorator functions.
One of the problems I have with decorators in Java is how they're everywhere. This strongly suggests a language feature taken far far past their original envisaged use which usually means they're filling a need the language doesn't otherwise meet.
Yep! You can clean up the any's, I'll show how in a future video. They're actually perfectly type-safe, I can't find any way to break them at the moment.
generic const and decorators, oh man nice features!
I'm not sure that decorators will revive React class components and to be honest, I hope they don't. As far as I know React team mentioned in the past that classes are problematic in JS since they are just syntactic sugar and they cause problems with bundling and minifying. I don't see React classes coming back and I hope that React team does deprecate them in the future.
Regarding decorators in general, I don't do much OOP really so I don't write classes, but they do make things tidy and more readable, that's for sure. When I had to write MobX stores, using decorators just produced way cleaner and more understandable code.
Hey :D