This TypeScript Trick Blew my Mind

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

Josh tried coding

Josh tried coding

5 ай бұрын

I just love learning stuff like this. Super handy for these use-cases and these just make your app that much nicer to develop. Really hope you enjoy it as much as I do!!
Maybe the best tech newsletter???: www.joshtriedcoding.com/
-- my links
Discord: / discord
GitHub: github.com/joschan21

Пікірлер: 101
@albert21994
@albert21994 5 ай бұрын
introducing this to my typescript brain is like adding letters to math in 5th grade
@scottz6830
@scottz6830 5 ай бұрын
To add some more flexibility, you could infer like this `${string}-${infer R}-${string}`. that way any dashed dashed styled string would extract the color
@eqprog
@eqprog 5 ай бұрын
Thanks. This is arguably less typesafe though. Depends on the context in which the color is being used.
@florianbopp187
@florianbopp187 5 ай бұрын
even more flexibility could be having a delimiter as a second param like this: type ExtractColor = T extends `${infer W1}${D}${infer Rest}` ? W1 | ExtractColor : T
@atmosph
@atmosph 5 ай бұрын
today i learned about template literal types: type lang = 'en' | 'de' type country = 'us' | 'gb' | 'de' type fullCode = `${lang}-${country}` and this feature you showed looks like an _upgraded_ version of the template literal types, which is going to solve several issues while writing type-safe code. thank you so much! ^^
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
that's really cool, thanks for sharing!
@atmosph
@atmosph 5 ай бұрын
@@joshtriedcoding you are welcome!
@froxx93
@froxx93 5 ай бұрын
I had no idea about this. Amazing. Thanks!
@robwatson826
@robwatson826 4 ай бұрын
The more you know. Typescript has some amazing features. Thanks for sharing!
@RicoGrof
@RicoGrof 4 ай бұрын
this is why Typescript is programming language, not just type checker. some guy even create Add type template
@asdfasdfuhf
@asdfasdfuhf 5 ай бұрын
Okay, this actually blew my mind, I didn't know you could do this with typescript.
@paulbruno4953
@paulbruno4953 5 ай бұрын
Eloquent solution, good job!
@GeneralDeD9963
@GeneralDeD9963 5 ай бұрын
Thank you Josh
@codewithguillaume
@codewithguillaume 5 ай бұрын
Josh: you are my favorite channel for coding.
@francoandre307
@francoandre307 5 ай бұрын
i need learn more typescript, this video blow my mind
@mubin-ansari
@mubin-ansari 5 ай бұрын
Thanks, this is going to help a lot in Advent of Typescript challenges!
@AntNZ
@AntNZ 5 ай бұрын
Omg this just save me. I having been going in circles trying to figure out how to extract and validate string values in nextjs search params
@Luxcium
@Luxcium 4 ай бұрын
This is the most underrated KZbinr in the coding space… I think he is so much underrated and talented I will still say that he is underrated after he has is Gold Button because he has the best energy and enthusiasm but he has the ability to make it not just fun and easy to understand but he makes it interesting for any level… you can be intermediate and not have the impression he is going slow for the n00b and yet you can be a beginner and not be lost… I think this guy has some great skills and he knows it and he makes everyone benefit from his knowledge and he has such a positive attitude 🎉🎉🎉🎉 I would love to have my membership card of his fan club 😅😅😅😅
@livedreamsg
@livedreamsg 3 ай бұрын
This is really cool! But I've never run into a situation where I needed it. I'd use an enum for this.
@joe-skeen
@joe-skeen 5 ай бұрын
Having used TypeScript from day 1 of its release and considering myself an "advanced" user, I still found myself with multiple mind-blown moments watching this
@pqnet84
@pqnet84 4 ай бұрын
day 1 typescript didn't have a lot of those tricks
@ARKGAMING
@ARKGAMING 5 ай бұрын
This is a really cool feature
@super_kenil7941
@super_kenil7941 5 ай бұрын
Woahh, that's actually a neat thing 🎉. Loved it
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
cheers!
@liberalwrecker949
@liberalwrecker949 5 ай бұрын
Why not use an object as a map and get more flexibility? Const colors = { red: { 500: “text-red-500”, 400: “text-red-400” } } as const Type Color = colors[string] Type Darkness = colors[string][number] Function findColor(color: Color, darkness: Darkness) { return colors[color][darkness] }
@sagecoder8802
@sagecoder8802 4 ай бұрын
Nice idea but not working. const colors = { red: { 500: 'text-red-500', }, blue: { 300: 'text-blue-300', }, } as const; type Color = keyof typeof colors; type Darkness = keyof (typeof colors)[C]; function findColor(color: P, darkness: T) { return colors[color][darkness]; } findColor('blue', 300); This will even predict/autocomplete the darkness parameter based off the color parameter.
@SonAyoD
@SonAyoD 5 ай бұрын
Great tip
@josemfcheo
@josemfcheo 4 ай бұрын
A subscriber earned here
@InMemoryOfNeo
@InMemoryOfNeo 5 ай бұрын
when i watch your videos my brain is blowing
@ViiOnC
@ViiOnC 5 ай бұрын
someone has been doing typescript advent
@IroshaHewage
@IroshaHewage 5 ай бұрын
hey josh. could you make a video sharing your thoughts on stylex. anyway i love your videos ❤
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
good idea!!
@CrankyBarbar1an
@CrankyBarbar1an 5 ай бұрын
OH. MY. GOD. IT HONESTLY BLEW MY MIND TOO.
@codernerd7076
@codernerd7076 5 ай бұрын
// Wishing you a festive season full of joy! Massive thanks for a year packed with stellar coding content! 🎉
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
Thanks so much, happy holiday season to you too!!
@salihyil2
@salihyil2 5 ай бұрын
Where did you see this code?
@ertyuiopos3942
@ertyuiopos3942 2 ай бұрын
thats prerrty cool!
@neoish
@neoish 5 ай бұрын
Thanks quite useful but also This should be a short.
@yaswanthgosula2468
@yaswanthgosula2468 5 ай бұрын
Advent of typescript
@suyashgulati
@suyashgulati 5 ай бұрын
What is advent of typescript?
@sefatanam
@sefatanam 5 ай бұрын
awesome 😮😮😮
@avneet12284
@avneet12284 5 ай бұрын
So good
@OllyWood688
@OllyWood688 5 ай бұрын
Hahaha so this can cause dev/compile time errors when matching on a dynamic source and that source changes? Awesome, I'm absolutely going to annoy my colleagues with that :D
@ShadoFXPerino
@ShadoFXPerino 4 ай бұрын
The point of TS is to cause as many compile time errors as possible so that less problems happen in the real world.
@TekExplorer
@TekExplorer 5 ай бұрын
this is the weirdest type system ive ever seen
@CodeZakk
@CodeZakk 5 ай бұрын
hi thanks for this video. i have one question why don't we use redux with nextjs. i have never seen a tutorial which uses nextjs with redux can you explain to me this thanks!!!
@edhahaz
@edhahaz 5 ай бұрын
I love javascript! This is not possible in any other language, I wonder why
@7n7o
@7n7o 5 ай бұрын
1, this is typescript, not javascript 2, many many languages have similar powerful type systems.
@TejasThombare-rl4du
@TejasThombare-rl4du 5 ай бұрын
Waiting for new advanced
@facundoflores4763
@facundoflores4763 5 ай бұрын
Somebody played with advent of typescript
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
haven't had the time for it yet, sounds awesome tho
@facundoflores4763
@facundoflores4763 5 ай бұрын
@@joshtriedcoding it is really good!
@murtadha96
@murtadha96 5 ай бұрын
I have a feeling that your use case revolved around passing tailwind classes as props safely :))
@joshtriedcoding
@joshtriedcoding 5 ай бұрын
yep! Pretty much the same use case as in the video, and I was so glad once it worked well
@reed6514
@reed6514 5 ай бұрын
How's the runtime performance as the list of colors grows? How's it compare to regex?
@scottz6830
@scottz6830 5 ай бұрын
This is typescript, there is no runtime
@user-yx4rj5pf9j
@user-yx4rj5pf9j 5 ай бұрын
my brain hurts 🫨
@karangill2065
@karangill2065 5 ай бұрын
At 1:14 we could've just turned the function into generic type and used keyof typeof from data passed.
@helleye311
@helleye311 5 ай бұрын
I really wish this was as easy in actual code not in typescript. For this you'd basically need to text.split("-")[1], but for more complicated things the only way is writing regex with custom named capture groups, and then destructuring that. But then typescript complains that the match could be null or some groups could not get matched, and for numbers you need to parse them manually later, it's a huge mess. basically, give me reverse string literals where you just go text.extract(`text-${const color}-500`); and you get color out (or undefined/null/empty string if it didn't match). Trademark pending.
@sp3ctum
@sp3ctum 5 ай бұрын
I agree, currently I don't know of a great option for this. Each one has downsides: - string.split() is hacky but works for simple cases - regex is cursed and can be hard to debug - a parser combinator library is a nice option but not every project wants to add a dependency just for this
@reed6514
@reed6514 5 ай бұрын
As an alternative to the extract template strings, you could write a function like fn(string input_text, ...must_match) Where args may be either strings or arrays of strings. If string args match input_text at the same character index, then continue. And if one of the strings in the array args matches the input_text starting at the same character index, also continue. But I'd rather use regex.
@XxZeldaxXXxLinkxX
@XxZeldaxXXxLinkxX 4 ай бұрын
Yo dog I heard you liked types in your scripts, so I put scripts in your types so you can script your types while you type your scripts
@rikschaaf
@rikschaaf 5 ай бұрын
Or you could use enums.
@holakonoob
@holakonoob 5 ай бұрын
what about if its -700 or -400 ...
@Zhundah
@Zhundah 5 ай бұрын
You could use `text-${infer R}-${number}` or even `${string}-${infer R}-${number}`, `${'text' | 'bg'}-${infer R}-${number}`. The possibilities are endless.
@big-jo89
@big-jo89 5 ай бұрын
in his example, it should return the given string as is
@O_Eduardo
@O_Eduardo 5 ай бұрын
Nice to know about the wizardry.... but for everyone seeing this, never, ever put that on professional code base... Typescript is creating more issues than it is solving. Code is not meant to be fun, its about maintanability..
@ReuelTeodoro
@ReuelTeodoro 5 ай бұрын
I’m confused why you added ‘number’ to type of colors
@super_kenil7941
@super_kenil7941 5 ай бұрын
It was an index of an array, from my guess. Line if you want a specific value from an array dynamically, you would have to write const foundItem = myArray[index]
@arisarsenkashari5308
@arisarsenkashari5308 5 ай бұрын
it refers to item positions in the array
@hossamkamal2459
@hossamkamal2459 5 ай бұрын
you can understand it like this , (number type is the set of all possible numbers) so what he did is accessing the array with all possible indices
@qorzzz9252
@qorzzz9252 5 ай бұрын
The functionality you are showing (generics and infer keyword) is great, but the example you are using to do so is so bad lol.
@suyashgulati
@suyashgulati 5 ай бұрын
Can you suggest a good example? Particularly for infer keyword
@GraphX02
@GraphX02 5 ай бұрын
​@@suyashgulati Infer can be used in many cases in typescript. You can infer the arguments, return type, values in array/objects and much more.
@Irakli008
@Irakli008 5 ай бұрын
It’s common knowledge that JOSH’S OPINION is WRONG and his EXAMPLES are BAD /s
@darkmift
@darkmift 5 ай бұрын
He's out here sharing knowledge which benefits many, You put a comment with no value. Offer an alternative instead. Contribute something of actual value.
@Phanboy
@Phanboy 5 ай бұрын
As someone with no baseline, this example was great 👍
@user-hb6yb6bu8n
@user-hb6yb6bu8n 5 ай бұрын
Josh, I'm fetching on the server with trpc but mutating on the client with react query and trpc, how to revalidate data in this case?
@27sosite73
@27sosite73 5 ай бұрын
will ai replace me today or tomorrow?
@joelapablaza7722
@joelapablaza7722 5 ай бұрын
I think this is already too much. TypeScript is inspired by C# to make the work more robust yet agile. And this is already too much... it doesn't make sense
@somefin3322
@somefin3322 5 ай бұрын
Makes me really appreciate C# even more.
@filipelinharesplus
@filipelinharesplus 5 ай бұрын
omfg
@FranFiori94
@FranFiori94 5 ай бұрын
What is this example lmao
@Mayeru
@Mayeru 5 ай бұрын
today i learned that Typescript needs to implement enums.
@mobix25
@mobix25 5 ай бұрын
hey josh. if it's not too much trouble can you create a project with a real backend service hosted on our pc and make the API accessible publicly. like creating a real server, and there is no full project on YT so PLEASE.
@Irakli008
@Irakli008 5 ай бұрын
Fun and neat trick, but this is some typescript acrobatics. I would question how sensible it is to do this in a professional environment, with others who might have to work with this code.
@tiltMOD
@tiltMOD 5 ай бұрын
I wonder what's the problem with TS design/documentation that even more seasoned developers from time to time just "find out" new things about it. It's a trend that I haven't seen in other languages/libraries nearly as often as in TS.
@RupluttajaGames
@RupluttajaGames 5 ай бұрын
It's all about click bait
@genechristiansomoza4931
@genechristiansomoza4931 5 ай бұрын
Isn't that easy in javascript. Throw error if string is not in array.
@brain5853
@brain5853 5 ай бұрын
Cool trick but readability is horrible. If someone unfamiliar with the concept took a look at that function parameter typing he'd be like 'wut'
@codeAbinash
@codeAbinash 5 ай бұрын
Typescript is a Joke and I Love it 😅.
@yohendryy
@yohendryy 5 ай бұрын
FOR FUCK SAKE JUST USE A MAP
@venicebeachsurfer
@venicebeachsurfer 5 ай бұрын
You glossed over too quickly.. .what does "[number]" explain here? Like, what/how does that work...
@Nicolas-dz1pn
@Nicolas-dz1pn 5 ай бұрын
Lets say I have an array of strings, array[number] would try infer all the types inside that array. In his case he was using "as const" so the types would change to immutable ones and for that reason the array[number] gives us a union of every string in the array instead of just the generic type string. type ArrayToUnion = T[number] const colors = ["black", "white"] as const; type ColorUnion = ArrayToUnion // -> 'black' | 'white' I might have missed some points because I didn't actually study that trick properly, just happened to stumble upon that when I was trying to convert a whole array into a union type
@mnik0128
@mnik0128 5 ай бұрын
Imaginary problems. Please stop messing editor speed with complex types that not solve any real problems
@studiowebselect
@studiowebselect 5 ай бұрын
kzbin.info/www/bejne/iqS8lnWJa9tnqJosi=8R2-wyjth7p4_4jj&t=239 instead of S you can use "Never" and if the syntax is not good it will throw an typescript error
7 Awesome TypeScript Types You Should Know
8:57
Josh tried coding
Рет қаралды 75 М.
How Did I Not Know This TypeScript Trick Earlier??!
9:11
Josh tried coding
Рет қаралды 200 М.
КАРМАНЧИК 2 СЕЗОН 5 СЕРИЯ
27:21
Inter Production
Рет қаралды 538 М.
Trágico final :(
01:00
Juan De Dios Pantoja
Рет қаралды 33 МЛН
Cat story: from hate to love! 😻 #cat #cute #kitten
00:40
Stocat
Рет қаралды 10 МЛН
Updates Like These Make Tailwind So Fun
8:00
Josh tried coding
Рет қаралды 69 М.
Rust for TypeScript devs : Borrow Checker
8:49
ThePrimeagen
Рет қаралды 211 М.
Understand Angular Signals in 20 Minutes
20:17
Igor Sedov
Рет қаралды 4,6 М.
We Need to Talk About Redis.
14:55
Josh tried coding
Рет қаралды 87 М.
LocalStorage was a mistake...
5:33
Josh tried coding
Рет қаралды 44 М.
Enums considered harmful
9:23
Matt Pocock
Рет қаралды 191 М.
The Truth About Facebook's "Tailwind Killer"
6:48
Josh tried coding
Рет қаралды 42 М.
The Problem With UUIDs
6:36
Josh tried coding
Рет қаралды 66 М.
Type your functions in TypeScript and SAVE TIME
8:31
ThePrimeTime
Рет қаралды 47 М.
ПК с Авито за 3000р
0:58
ЖЕЛЕЗНЫЙ КОРОЛЬ
Рет қаралды 1,3 МЛН
Обзор игрового компьютера Макса 2в1
23:34
Что еще за Smartisan?
0:49
Не шарю!
Рет қаралды 306 М.
Apple, как вас уделал Тюменский бренд CaseGuru? Конец удивил #caseguru #кейсгуру #наушники
0:54
CaseGuru / Наушники / Пылесосы / Смарт-часы /
Рет қаралды 4,3 МЛН