TypeScript Wizardry: Recursive Template Literals

  Рет қаралды 36,357

Tech Talks with Simon

Tech Talks with Simon

Жыл бұрын

In this one, I'll show you some template literal magic for accessing deeply nested objects in TypeScript. If you like pushing the boundaries of type-level programming, this video is for you!

Пікірлер: 129
@sstur
@sstur Жыл бұрын
The code from this video can be found here: bit.ly/iuebsku
@freespeech515
@freespeech515 Жыл бұрын
type script sucks for front end
@YilmazDurmaz
@YilmazDurmaz Жыл бұрын
I use types all the time (many languages) but I was not even aware "type-level programming" is a thing :) TypeScript is at another level.
@Microphunktv-jb3kj
@Microphunktv-jb3kj Жыл бұрын
thats why javascript/typescript sucks... initially it feels cool and easy language.. but the learning curve goes up and up overtime, the more complicated ur project will become... but in lower lvl languages, the learning curve is upfront and will not go up overtime and hard things are easy to do, because they have proper standard libraries
@W1ngSMC
@W1ngSMC Жыл бұрын
You haven't done template meta programming in C++ then (or Rust macros). I envy you.
@tsukinoko_kun
@tsukinoko_kun Жыл бұрын
I like this in TypeScript. It is very useful for library code. But you have to do unit tests to ensure that your JavaScript code does the same thing as your types say.
@sstur
@sstur Жыл бұрын
@@tsukinoko_kun Yes, this is a good point! After you get the types working you have to get the implementation working (or the other way around) and then you need to make sure they stay in sync. It really is like two languages in the same source code!
@oscarcarlen5952
@oscarcarlen5952 Жыл бұрын
@@sstur Zod is your friend
@confused_horse
@confused_horse Жыл бұрын
I was casually watching this in the living room and was really excited because it's just extraordinarily good content. But as soon as I was done I turned around to see my girl friend judging me. She called me a nerd and now I am happy in two ways. :> Thank you for sharing this and "yolo"
@brigadafitness5833
@brigadafitness5833 Жыл бұрын
Great content man, I think this type of advanced ts videos are really valuable, and it's not something you find often (at least with this quality). Keep the great job.
@sstur
@sstur Жыл бұрын
Thanks! I really do like that folks are into this advanced TS stuff. Have more vids coming soon!
@arogueotaku
@arogueotaku Жыл бұрын
Damn dude. That big brain move of intersecting string with the T[K] blew my mind. This video is going straight to my favorites playlist. You got a sub from me.
@rahul38474
@rahul38474 5 күн бұрын
I did something similar for another project, I made K extends string the outermost ternary operation so that in the true branch I didn’t need to do K & string, as in that branch K is narrowed to some string type. I used this type (I called it dot path) to map keys of one type to keys of another type based on a suffix in each key. Type level programming is my favorite feature of TypeScript (also probably the only feature I like tbh) because it feels like doing a proof, and also because the literal types make for a really good developer experience since the LSP can suggest strings from that type.
@maximemondello6174
@maximemondello6174 Ай бұрын
This video is Amazing ! I needed a lite translation hook for my project and didn't want to fiddle with libraries for it. This is just perfect! I adapted it to be able to loop trough several files of translate keys and it works wonderfully ! Thank you for that!
@gnarusg8708
@gnarusg8708 Жыл бұрын
Incidentally I needed something like this for work a few weeks ago. Found some stuff on Stack overflow, but this is the easiest solution to this problem I've found. Thank you. Only way this video could be better is if you addressed how to have multiple "stop" value types, string in this example, like string | number | string[], but then infer each type from the multiple addressed to right path key. Hopefully that made sense. I don't even know how possible that is but I'm curious to know. It's rare that KZbin recommends video this well. Subscribed. Great video!
@webbae
@webbae Жыл бұрын
Cool video Simon. I learned a lot just in the first 5 min. Had to rewind a few times in there hehe. Audio sounds great too!
@sstur
@sstur Жыл бұрын
Thanks man! Appreciate you checking it out!
@yuukidename403
@yuukidename403 Жыл бұрын
I know this is mainly a demonstration of advanced TS features, and it also helps when having to write type declarations for existing libraries. And sometimes it's the kind of API you want to have. But for new code, personally I would think about keeping it simple and just use e.g. t().greetings.morning instead of t("greetings morning"), where t = l => locales[l] (which is even one character shorter). This way no recursion is required and you get the same autocomplete suggestions. And you'll also get the exact type at given key for free, which somebody in the comments suggested could be used parameters etc.
@seftikara651
@seftikara651 Жыл бұрын
true, especially if everything is statically hard-coded within the app. but, maybe, the video approach, by using parameterized input, would be useful if the localization (in this case) are not entirely hard-coded within the program and could be imported from external sources, and also if that each keys are not strictly required. so that, you can define the default locale and its utilities just as in the video to provide code completion, etc., and freely plug optional locale after. And any not-found keywords from optional locales will fallback to the default one, without the need of implementing null-check (on each calls), etc. this also means that, if this is a web app, all locales doesn't have to be bundled to the main app for the user to use. The app could fetch it separately as needed.
@aenguswright7336
@aenguswright7336 Жыл бұрын
The trouble with this approach is that in the case of internationalization, it would be much harder to write a fallback case since you have to know at the time that you fetch the object tree if something will fall back, rather than at the time of access. This would mean some complex recursive function to fetch fallbacks at time of fetch, which you would have to pay every time you called the function at runtime, rather than at worst only on the occasions you tried to access a node which didn't exist and at best, only in development.
@EverRusting
@EverRusting 6 ай бұрын
I get that but i18n libraries usually work with path strings...
@aram5642
@aram5642 Жыл бұрын
Fantastic! Just in time for me, but I also love the way you reason about it.
@sstur
@sstur Жыл бұрын
Thanks Ar Am!
@daniellynch3724
@daniellynch3724 Жыл бұрын
This is amazing black magic and I’m glad I watched the video. If I ever saw anyone submit anything remotely similar to this in a PR it would get a Deny so fast my left click would break the sound barrier.
@SecularDarwinism
@SecularDarwinism Жыл бұрын
This is definitely my jam. Have stumbled upon many of these, what appeared to me to be roadblocks, glad to see they are traversable.
@dolevgo8535
@dolevgo8535 Жыл бұрын
Great video! One thing I would've done differently(and i'd love to hear your opinion) is- instead of manipulating the key of the mapped type, I would do the key-mapping-shenanigans you did in the values of the mapped type, then indexed using [keyof T]. it would probably be cleaner, using both sides of the object, and i also think you wouldn't need the second intersection at 11:50 since the return type wouldn't be a PropertyKey, rather a string(as the values would only be strings) its a slight knitpicking, would love to hear your opinion still, loved seeing you going through the problem, looking forward to more content!
@sstur
@sstur Жыл бұрын
Thanks Dolevgo! I believe you're right that I could have used the value side of each property instead of mapping the key. Actually, before we had "key remapping" (prior to TS 4.1) we had to do it using the value side. I'm not 100% sure that would eliminate the need for `& string` but I should poke around and see what I come up with and post back here. Thanks!
@Jamiered18
@Jamiered18 Жыл бұрын
Ah, excellent! When I came upon this problem years ago, this was not possible yet in Typescript. I had to solve the problem in a more janky way. But this is so simple and sensible now, I can rewrite it nicely, thank you
@TheRhopsody
@TheRhopsody Жыл бұрын
This is amazing insight to me. Thank you. 😊
@bamboo6044
@bamboo6044 Жыл бұрын
I agree with most comments, I would like to see more TS content, very interesting and useful!
@Athet0s1s
@Athet0s1s 4 ай бұрын
I actually used this in our company to name the fields in the api responses as we get Keys that are in objects or arrays, and we use them parsed in a specific way (with __ instead of .) and It was so difficult for me to manage to do this. I think this is greatly explained and would've been so Happy to find this video when I did this 😂
@kylclrk
@kylclrk Жыл бұрын
This is fantastic. Keep it up!
@TheTom265
@TheTom265 4 ай бұрын
Brilliant. Thank you!!
@trongvinhnguyen6366
@trongvinhnguyen6366 Жыл бұрын
I have though about this many times and though it was impossible in TS. Now you've clear my mind. Thank you!
@SuperRoli123
@SuperRoli123 Жыл бұрын
This type programming is awesome
@LucasPachecoF
@LucasPachecoF Жыл бұрын
Dude, that’s awesome. Definitely will help me out
@sstur
@sstur Жыл бұрын
Thanks Lucas!
@simpel8040
@simpel8040 Жыл бұрын
That was awesome!
@sstur
@sstur Жыл бұрын
Thanks Simpel!
@eltyo340
@eltyo340 Жыл бұрын
14:00 I'm glad I'm not the only one who writes "yolo" when writing dummy data/console logs
@Cinerable
@Cinerable Жыл бұрын
Great video! Thanks!
@ArashMotamedi
@ArashMotamedi Жыл бұрын
Awesome! Magic!
@sourishdutta9600
@sourishdutta9600 Жыл бұрын
Nice one. Create more like this. 👍
@MinorMood
@MinorMood Жыл бұрын
Man, very good, thanks for sharing! With the TS one actually have a huge boilerplate even before actually start coding - but it is definitely worth of that!
@benllshua
@benllshua Жыл бұрын
wow cool Utility type!!
@tosunabi1664
@tosunabi1664 Жыл бұрын
Piece of art for a new TS user.
@ARKGAMING
@ARKGAMING Жыл бұрын
This was a very interesting video. I really enjoyed it
@tezismith8795
@tezismith8795 4 ай бұрын
great explanation! I didn't know about that `K & string` trick, very useful :) thanks
@voyager_ll
@voyager_ll Жыл бұрын
Wow, that's crazy :D didn't know that was possible!
@_Karlsson
@_Karlsson Жыл бұрын
Legendary
@JesseBaker121
@JesseBaker121 Жыл бұрын
Great video, localws are always a pain and I've had this issue in the past. Very elegant solution
@artemkaratai8958
@artemkaratai8958 Жыл бұрын
subscribed and waiting for more :)
@paulborek9163
@paulborek9163 Жыл бұрын
Wow I am truly amazed by this video. I considered myself as a mid advanced typescript user, but I just never got my brain that far... hoping to see much more typescript from you. Great work there
@sstur
@sstur Жыл бұрын
Thanks Paul!
@Microphunktv-jb3kj
@Microphunktv-jb3kj Жыл бұрын
using typescript isnt a skill, but a chore
@Hagledesperado
@Hagledesperado Жыл бұрын
@@Microphunktv-jb3kj Then don't?
@76Freeman
@76Freeman Жыл бұрын
Wow great stuff. You've just gained a new subscriber :). I've been getting more and more into Typescript and I often struggle with recursion. I think the "variables" name in types aren't always the best :) things like K and T aren't very descriptive and it makes it really hard to understand what is going on :). I think one nice thing would be to comment the most challenging parts so you know what is going on. But I loved your process though, thank you very much the great video.
@jeromealtariba7339
@jeromealtariba7339 Жыл бұрын
these types might be very useful when creating sql queries, using nested relations, with an ORM such as typeorm. Very interesting thks
@matttamal8332
@matttamal8332 Жыл бұрын
This is fantastic stuff Simon. I usually have to bash my head against problems like this when I make generic utilities that are used across the code base. One the the most fun times I've had in programming was creating destructive interference to collapse an type-generated object to filter out other types. Out of curiosity, do you have any good sources for type leveling programming that I can reference or learn this kind of stuff from on a more structured and fundamental level?
@sstur
@sstur Жыл бұрын
Thanks Matt! I've heard good thing about type-level-typescript.com (but haven't been through it myself), check that out and let me know if it's awesome.
@matttamal8332
@matttamal8332 Жыл бұрын
@@sstur Awesome! I'll take a look into this! :)
@InMemoryOfNeo
@InMemoryOfNeo Жыл бұрын
Awesome 👌👏👏👏👏👏👏👏👏
@LeshkaSaD
@LeshkaSaD Жыл бұрын
very educational video 👍 would be great to see more videos about complex types in TS and you find a solution for them
@WorstmetJus91
@WorstmetJus91 Жыл бұрын
Very cool! React-hook-form I believe uses exactly this syntax to access form data but i do not know how they made the typing work. Perhaps worth the look? I know I will now!
@Vedmalex
@Vedmalex Жыл бұрын
Thanks for the video. Trying do something lake this without using recursive type… this solution cooler!
Жыл бұрын
Didn't know you could put string literals to generate keys! I was always wondering, how react solved "data-xyz" props. I was looking into its types, but couldn't find it there.. now I know it is some version of this!
@danieljulien4099
@danieljulien4099 Жыл бұрын
so great and horrific at the same time lol. my 1st encounter with type programming going so far. 🤯😭🔥
@sstur
@sstur Жыл бұрын
Haha, yes it's a bit horrific at first sight! and the rabbit hole goes deep. But TS is great for a lot of things, even if you don't go deep into type level programming!
@danieljulien4099
@danieljulien4099 Жыл бұрын
@@sstur yes! i learned A LOT watching your video + you explain very well, so thank you for that!
@EconomicsDomain
@EconomicsDomain 2 ай бұрын
Great explanations, but personally would frown if I saw this in a project. Mental gymnastics and cognitive overload ;)
@nestnik
@nestnik 24 күн бұрын
That's amazing! What resources can I use to level up my type-level programming skills?
@ofweb
@ofweb Жыл бұрын
That is a very nice explanation. Would it be possible to make the t function more strict on the return type? so that instead of just returning a string it returns a string litteral? so that when you add the key the complier already knows what the sting is and shows that on hover.
@stevenvaught9429
@stevenvaught9429 Жыл бұрын
If you do that, you're effectively writing the same logic in both js-land and type-land. You may be able to reify the type-land version and have code that can use that reified definition, but it wouldn't be doable without some library/plugin
@raymondmichael4987
@raymondmichael4987 Жыл бұрын
Thanks buddy 😮, this got me; Still getting my feet wet with Typescript 😊
@ionitaa
@ionitaa Жыл бұрын
Imagine geting hired somewhere and your first task is to debug this while Simon is no longer working there
@sstur
@sstur Жыл бұрын
😂 You've legit got a point here
@cipherxen2
@cipherxen2 Жыл бұрын
Caution: python junkies should not watch this video, it might break their brain
@nieczerwony
@nieczerwony Жыл бұрын
Tak Python anytime over any shit from MS.
@MirrorsEdgeGamer01
@MirrorsEdgeGamer01 Жыл бұрын
@@nieczerwony Microsoft is helping the Python team to increase speed.
@nieczerwony
@nieczerwony Жыл бұрын
@@MirrorsEdgeGamer01 Well as long as they don't own it.
@nazaka9904
@nazaka9904 Жыл бұрын
i see it right on the next day after doing exactly the same :)
@Nick-tv5pu
@Nick-tv5pu Жыл бұрын
Good heavens
@MaximeTrichard
@MaximeTrichard Жыл бұрын
How would you also allow "hello.greetings" for instance ? (stop the type mid-path) It can sometimes be useful, although this is not the case in your example obviously. Anyways, great explanation, thank you for that !
@seftikara651
@seftikara651 Жыл бұрын
you could change the ``` T[K] extends Record ? `${K & string}.${Keywords & string}` ``` part to ``` T[K] extends Record ? `${K & string}.${Keywords & string}` | K ``` the ```| K``` here inserts the bare(?) type along with the nested type. (unification) the complete one would look like this ``` type Keywords = keyof { [K in keyof T as T[K] extends string ? K : T[K] extends Record ? `${K & string}.${Keywords & string}` | K : never]: any; }; ``` **I changed PathInto to Keywords btw, fits better for me
@CottidaeSEA
@CottidaeSEA Жыл бұрын
This is honestly really cool. I just wish TypeScript wasn't JavaScript, because in the end you can just throw anything into whatever TypeScript function is created and watch it break. I know many who struggle with TypeScript due to IDE performance as well, which is unfortunate. More of an IDE problem though (and likely relying too much on inference).
@LewisCowles
@LewisCowles Жыл бұрын
Do you have any stats on what these "fancy types" do to build times?
@repe0
@repe0 Жыл бұрын
Many i18n libraries let you do this automatically. It will understand that there might be depth in your translation.json
@shadowsir
@shadowsir Жыл бұрын
Except this will throw a compile time error if the translation key doesn't exist in stead of at runtime.
@senor_m6673
@senor_m6673 Жыл бұрын
​@@shadowsir i think thats what he meant, that for example i18next is already using this kind of functionality
@000TheMatheus000
@000TheMatheus000 Жыл бұрын
can you type the returntype of this function so it knows exactly wich string you are returning based on the key passed?
@sstur
@sstur Жыл бұрын
Yes, I believe this would be possible. But I don't know what the advantage to that would be. What do you have in mind?
@dolevgo8535
@dolevgo8535 Жыл бұрын
@@sstur A good use for it would be to know if there are mappings inside the return type(such as {user}), that way the developer would know to pass those parameters- or even enforce it in the function signature!
@sstur
@sstur Жыл бұрын
@@dolevgo8535 Ah, got it. Coincidentally I have a vid coming up that should help with this. I also have some examples that might help. Will post back here.
@enjay86
@enjay86 Жыл бұрын
au, my brain!
@HACKERMORE
@HACKERMORE Жыл бұрын
"T[K]" I'm sure people will try to backtrack a lot to understand this. It's still a pain in the ass 🤣🤣
@0xramon
@0xramon Жыл бұрын
been playing around with something similar, ended up with type DotNotation = { [K in keyof T]: T[K] extends object ? `${K & string}.${DotNotation}` : K & string; }[keyof T]; type Foo = DotNotation
@0xramon
@0xramon Жыл бұрын
can also extend it to filter out certain keys, for example ``` type Excluded = "sample" | "other"; type DotNotation = { [K in keyof T]: T[K] extends object ? `${K & string}.${DotNotation}` : `${K extends Excluded ? never : K & string}`; }[keyof T]; const x = { foo: "a", sample: "unreachable", bar: { other: "unreachable", zoo: "b", moo: "c", }, }; type Foo = DotNotation; ``` only `"foo", "bar.zoo", "bar.moo"` are available
@karlockert
@karlockert Жыл бұрын
Could perhaps ‘infer K’ be used instead of ‘& string’ to Get the types correctly and also provide some fallback?
@dokkenrox
@dokkenrox Жыл бұрын
Man, that's rough! LOL It's an elegant solution but it's not very legible. It seems like once we get to the level of complexity where we need to invoke the term "type-level programming" that Typescript's terse syntax doesn't always let you express things in a way that's suitable for maintainability. You see the same kind of shortcomings with complex regular expressions. It starts to feel like you would almost want an extended syntax to deal with that sort of thing. Some languages actually do have alternative ways to build regexes that are more verbose but easier to read. Maybe MS will do something similar for Typescript in the future.
@shadowsir
@shadowsir Жыл бұрын
Whoa, didn't know this was possible, great job explaining it! :D
@joppekoers3992
@joppekoers3992 Жыл бұрын
This was great! But please share the code so I dont have to image-to-text it.
@sstur
@sstur Жыл бұрын
The code from this video can be found here: bit.ly/iuebsku
@Giffeln
@Giffeln Жыл бұрын
Great video! My version for this case would be type PathTo = keyof { [K in keyof T as T[K] extends Record ? `${K & string}.${PathTo & string}` : K & string]: any; };
@shaikhdanish2793
@shaikhdanish2793 Жыл бұрын
Can we also program the object?
@Vali615
@Vali615 Жыл бұрын
Would be much easier to use a recursive function to generate those strings. If you add an extra level, you need to change all your code...
@alextrofimov8320
@alextrofimov8320 Жыл бұрын
Why do you need to do ": keyof. { [K in EXP]: any } "instead of ": EXP"?
@coolemur976
@coolemur976 Ай бұрын
All of that just to have some intellisence on (string): string 😁
@coffeeandbytes9854
@coffeeandbytes9854 Жыл бұрын
This is my issue with TypeScript tutorials, there are only two skill levels being taught: Absolute Beginner or Dark Wizard.
@dawid_dahl
@dawid_dahl 4 ай бұрын
This is starting to look like Haskell code, haha.
@disel920
@disel920 Жыл бұрын
Cool, my version without `& string` const data = { env: { name: "", payload: { price: 0, size: 0, }, }, }; type DataType = typeof data; type PathsInRecord = keyof { [KEY in keyof OBJ as OBJ[KEY] extends object ? KEY extends string | number ? PathsInRecord extends string ? KEY | `${KEY}.${PathsInRecord}` : never : never : KEY]: never; }; type res = PathsInRecord; const a: res = "env"; const a0: res = "env.name"; const a1: res = "env.payload"; const a2: res = "env.payload.price";
@andrepadez
@andrepadez Жыл бұрын
Thank you for this video, i was looking for something short and concise to show clients "why you shouldn't use TS"
@avneet12284
@avneet12284 Жыл бұрын
No repository link? Not good. But excellent video
@andrepadez
@andrepadez Жыл бұрын
typescript is insane, and not in a good way
@BobbyBundlez
@BobbyBundlez Жыл бұрын
i know. its still absolutely ridiculous to me. horrific level of yet more abstraction to fix a basic problem JS had from the beginning. being loosely typed lol
@dmitriynesterkin5672
@dmitriynesterkin5672 Жыл бұрын
This is a great example for why not to use Typescript. What exactly does the baby-sitting code accomplish? Imagine the amounts of time wasted writing, reading, and maintaining shit like this. Write plain JS and use tests to assert code quality.
@nicholasdenaro347
@nicholasdenaro347 Жыл бұрын
If it's a great example, please explain why this is bad. To me this looks fine. While it is moderately complex code, it does ensure "type" safety. Which part of it will need maintenance?
@dmitriynesterkin5672
@dmitriynesterkin5672 Жыл бұрын
​@@nicholasdenaro347 What exactly is the benefit of the code below? It took him more time to type that than the actual function. The snippet would work only for hard-coded objects and then a "special" t() function has to be used to make sure that correct properties are passed to get(). More code. It's better to just use get() directly and if a path is misspelled, then undefined will be returned, and if it is used, then an error will result and will have to be corrected. All of this is less time-expensive than creating hand-holding type overhead. type PathInto = keyof { [K in keyof T as T[K] extends string ? K : T[K] extends Record ? `${K & string}.${PathInto & string}` : never]: any;
@markemerson98
@markemerson98 Жыл бұрын
another reason i detest typescript...
@pawegraczyk6050
@pawegraczyk6050 Жыл бұрын
Useless
@BobbyBundlez
@BobbyBundlez Жыл бұрын
so lame lol. TS at this level takes the joy and fun out of literally everything
Infer is easier than you think
13:38
Matt Pocock
Рет қаралды 84 М.
TypeScript: tsconfig demystified!
22:32
Tech Talks with Simon
Рет қаралды 10 М.
Teenagers Show Kindness by Repairing Grandmother's Old Fence #shorts
00:37
Fabiosa Best Lifehacks
Рет қаралды 43 МЛН
Маленькая и средняя фанта
00:56
Multi DO Smile Russian
Рет қаралды 4,1 МЛН
О, сосисочки! (Или корейская уличная еда?)
00:32
Кушать Хочу
Рет қаралды 6 МЛН
How to use generics in TypeScript
11:46
Andrew Burgess
Рет қаралды 35 М.
Generics: The most intimidating TypeScript feature
18:19
Matt Pocock
Рет қаралды 159 М.
TypeScript Template Literal Types // So much power ☢️
5:18
TypeScript Enums are Bad // Alternatives to use
8:19
basarat
Рет қаралды 7 М.
How principled coders outperform the competition
11:11
Coderized
Рет қаралды 1,5 МЛН
as const: the most underrated TypeScript feature
5:38
Matt Pocock
Рет қаралды 108 М.
How Did I Not Know This TypeScript Trick Earlier??!
9:11
Josh tried coding
Рет қаралды 200 М.
TypeScript's Utility Types... Blazing fast
3:09
Matt Pocock
Рет қаралды 43 М.
Mapped Types - Advanced TypeScript
12:16
Dmytro Danylov
Рет қаралды 41 М.
Branded Types give you stronger input validation
9:22
Andrew Burgess
Рет қаралды 16 М.
What’s your charging level??
0:14
Татьяна Дука
Рет қаралды 6 МЛН
Дени против умной колонки😁
0:40
Deni & Mani
Рет қаралды 6 МЛН
С Какой Высоты Разобьётся NOKIA3310 ?!😳
0:43
Как я сделал домашний кинотеатр
0:41
RICARDO
Рет қаралды 1,4 МЛН