- 39
- 158 216
Typed Rocks
Switzerland
เข้าร่วมเมื่อ 8 มิ.ย. 2024
Everything regarding TypeScript and JavaScript, including advanced patterns, crazy things one can do with TypeScript the latest and greatest tools, and more can be found here.
This WILL CHANGE How You Work With Strings - Advanced TypeScript Magic!
Code: github.com/typed-rocks/typescript/blob/main/length.ts
Sometimes we want to restrict the length of a string and want to throw a compile time error when we pass strings which don't fit for certain use cases. Currently this is not possible using existing TypeScript types. That‘s why we will create our own types to achieve this.
0:00 Introduction
0:20 Length Utility
3:10 Compare Utility
6:40 MaxLength, MinLength, InRange Type
9:40 Usage in Functions
14:40 Outro
Sometimes we want to restrict the length of a string and want to throw a compile time error when we pass strings which don't fit for certain use cases. Currently this is not possible using existing TypeScript types. That‘s why we will create our own types to achieve this.
0:00 Introduction
0:20 Length Utility
3:10 Compare Utility
6:40 MaxLength, MinLength, InRange Type
9:40 Usage in Functions
14:40 Outro
มุมมอง: 7 583
วีดีโอ
No More Unreadable Types! A Cleaner, Functional Way to Build TypeScript Types
มุมมอง 6K21 วันที่ผ่านมา
Plugin: marketplace.visualstudio.com/items?itemName=chwoerz.type-buddy web app: typed-rocks.github.io/type-buddy/ Github repo: github.com/typed-rocks/type-buddy Until now we always had to use ternaries for complex conditional types. But this gets complex quite fast. That's where Type Buddy steps in. By using this plugin, we can create complex conditional types with ease. 0:00 Intro 0:15 The Iss...
In SIX LINES of Code I Fixed Two Major NodeJS TypeScript Issues
มุมมอง 7Kหลายเดือนก่อน
Code: github.com/typed-rocks/typescript/blob/main/promisify.ts The promisify utility in node has two major flaws in its type definitions. So let's fix them in six lines of code. 0:00 Intro 0:11 The issue 3:50 The solution 8:40 Try the solution 10:30 Outro
The AutoComplete Utility Type: Powerful Suggestions Without Restrictions - Advanced TypeScript
มุมมอง 4.7Kหลายเดือนก่อน
github.com/typed-rocks/typescript/blob/main/autocomplete.ts Sometimes we want to provide some autocomplete functionality to a string type without restricting the type itself. In TypeScript we can create a utility type which provides such functionality in one line of code. So let's do that. 0:00 Intro 0:11 The problem 2:10 The solution 4:50 Outro
Stop Wasting Time and Effort: Automate String Types with These TypeScript Tricks
มุมมอง 5Kหลายเดือนก่อน
infer: th-cam.com/video/vjsmv7M1iBE/w-d-xo.html intrinsic: th-cam.com/video/B3LDiHl7pBI/w-d-xo.html We should rarely repeat ourselves when creating types in TypeScript. By using template literals, we can reuse our types and let TypeScript create new ones easily for us. No more errors, duplicated code or wrong types. 0:00 Intro 0:20 The initial type 2:04 Implementation 6:45 Outro
TypeScript Magic: Console.log FINALLY Typed!
มุมมอง 3.7Kหลายเดือนก่อน
infer: th-cam.com/video/vjsmv7M1iBE/w-d-xo.html Code: github.com/typed-rocks/typescript/blob/main/console.ts Console.log is used by almost every developer on a daily basis. But sadly it's not as properly typed as it could be. So let's change that and add proper typings to that essential tool. 0:00 Introduction 0:52 The Issue 2:43 Helper Types 6:15 The Main Type 13:00 Testing the typings 15:50 O...
TypeScript Magic: Automatically Extract Property Types into Unions
มุมมอง 3.4K2 หลายเดือนก่อน
Sometimes we need to keep track of all the types a certain named property like "id" has in a complex nested type. While we could do this manually, this is quite error prone. So this is why in this video we create a utility type which finds all the types a certain property has in a given type. 0:00 Introduction 0:48 The problem 2:00 Implement the solution 7:15 It works 9:30 Outro
How To Add Custom Intrinsic Types To TypeScript
มุมมอง 3K2 หลายเดือนก่อน
github.com/typed-rocks/patch-ts www.npmjs.com/package/patch-ts TypeScript uses intrinsic types internally to create powerful types which would be almost impossible to create in only types. Sadly TypeScript does not provide a functionality to add intrinsic types yourself. That's why I've created patch-ts. A cli tool which patches the TypeScript compiler to also support user defined intrinsic typ...
Let‘s Understand Intrinsic Types in TypeScript by Building Them
มุมมอง 5K2 หลายเดือนก่อน
Intrinsic types are a special kind of type in TypeScript. They are handled inside the TypeScript compiler. In this video we will dive deep into the bits and pieces of the TypeScript compiler and will even create our own intrinsic type by building a local version of TypeScript. 0:00 Intro 0:24 Regular vs intrinsic types 1:20 intrinsic types in checker.ts 3:50 Add intrinsic SnakeCase type 7:25 Bu...
I BUILT a GAME in TypeScript TYPES!
มุมมอง 4.1K3 หลายเดือนก่อน
In this video we will do something completely useless but extremely funny. We will build a fully functional tic-tac-toe gaming only using TypeScript types. 0:00 Intro 0:13 Helper Types 4:53 Implement the Important Types 12:40 Build The Final TypeTacToe 15:26 Play The Game 16:26: Outro
STOP Using Tsc and Node To Run TypeScript Use THIS instead - Supercharge Your Workflow
มุมมอง 1.7K3 หลายเดือนก่อน
vscode extension: th-cam.com/video/GqWaXfuoUYM/w-d-xo.html There are many great open source projects on Github. But my personal favorite, especially for TypeScript development is tsx. A cli which is a drop-in replacement for nodejs which lets you execute almost any TypeScript file without having to worry about anything. Because I really enjoy using that I've decided to sponsor the author of thi...
You NEED This IDE Plugin For TypeScript Type Development
มุมมอง 3.3K3 หลายเดือนก่อน
VSCode: github.com/orta/vscode-twoslash-queries Jetbrains: plugins.jetbrains.com/plugin/23294-witt typescript-type-hints-like-in-the-ts-playground Neovim: github.com/typed-rocks/witt-neovim I often get asked, what kind of plugin I'm using to get the resolved types right inside my editor. This video should answer these question, once and for all :) 0:00 Intro 0:20 VSCode 0:47 Jetbrains 1:10 Neov...
Let's Fix The Fatal Flaw in TypeScript's Union Types!
มุมมอง 23K3 หลายเดือนก่อน
Code: github.com/typed-rocks/typescript/blob/main/one_of.ts never type: th-cam.com/video/TBxln_ERlSE/w-d-xo.html recursive types: th-cam.com/video/Bqe_5-zvk1U/w-d-xo.html& Union types in TypeScript are great, most of the time. But sometimes we want to be restricted to use only one of the types in the union. TypeScript itself doesn't provide such a type which can lead to many issues when not add...
Get INSTANT Inline TypeScript Results in Neovim with This New Plugin
มุมมอง 1.9K4 หลายเดือนก่อน
Neovim plugin: github.com/typed-rocks/ts-worksheet-neovim vscode plugin: marketplace.visualstudio.com/items?itemName=chwoerz.ts-worksheet Often we need to just quickly try something in JavaScript or TypeScript and see the output of our code. With this plugin you no longer have to use console.log and the terminal to run your code but can just see the result of your variables and expressions righ...
This NEW VSCode Extension Every TypeScript Developer Needs To Try - Full Node, Deno and Bun Support
มุมมอง 5K4 หลายเดือนก่อน
This NEW VSCode Extension Every TypeScript Developer Needs To Try - Full Node, Deno and Bun Support
The Craziest TypeScript Types Video You Will Ever See - The Pinnacle of Advanced Type Wizardry!
มุมมอง 4.2K4 หลายเดือนก่อน
The Craziest TypeScript Types Video You Will Ever See - The Pinnacle of Advanced Type Wizardry!
Don‘t Use Readonly in TypeScript! Let‘s Build A Better Advanced One!
มุมมอง 2.8K4 หลายเดือนก่อน
Don‘t Use Readonly in TypeScript! Let‘s Build A Better Advanced One!
OpenAPI + Zod: Generate The Ultimate TypeScript API Clients Automatically
มุมมอง 6K4 หลายเดือนก่อน
OpenAPI Zod: Generate The Ultimate TypeScript API Clients Automatically
Master Every TSConfig With This Command: Reveal The Complete TypeScript Configuration with Ease
มุมมอง 9495 หลายเดือนก่อน
Master Every TSConfig With This Command: Reveal The Complete TypeScript Configuration with Ease
Fix the Fetch Type: Let's Add Auto-Completion and Perfect Type Safety to It in TypeScript
มุมมอง 5K5 หลายเดือนก่อน
Fix the Fetch Type: Let's Add Auto-Completion and Perfect Type Safety to It in TypeScript
Fix All Issues of Primitive Types: Achieve Perfect Type-Safety with Branded Types in TypeScript
มุมมอง 6K5 หลายเดือนก่อน
Fix All Issues of Primitive Types: Achieve Perfect Type-Safety with Branded Types in TypeScript
Let‘s Fix Unmaintainable Types: Automatically Transform Legacy Types in TypeScript with Ease
มุมมอง 13K5 หลายเดือนก่อน
Let‘s Fix Unmaintainable Types: Automatically Transform Legacy Types in TypeScript with Ease
The Never Type Explained: Everything You Need To Know - Advanced TypeScript
มุมมอง 1.9K5 หลายเดือนก่อน
The Never Type Explained: Everything You Need To Know - Advanced TypeScript
Mapped Types Explained: Keep Your Types in Sync Automatically - Advanced TypeScript
มุมมอง 7K6 หลายเดือนก่อน
Mapped Types Explained: Keep Your Types in Sync Automatically - Advanced TypeScript
Exploring the Power of Template Literals: An Overlooked Feature - Advanced TypeScript
มุมมอง 2.4K6 หลายเดือนก่อน
Exploring the Power of Template Literals: An Overlooked Feature - Advanced TypeScript
From Snakes 🐍 To Camels 🐫 - Create the CamelCase Type in TypeScript
มุมมอง 1K6 หลายเดือนก่อน
From Snakes 🐍 To Camels 🐫 - Create the CamelCase Type in TypeScript
The Tuple Utility Type - Complex Tuples in TypeScript made EASY
มุมมอง 7806 หลายเดือนก่อน
The Tuple Utility Type - Complex Tuples in TypeScript made EASY
MASTERING Type Manipulation in TypeScript Using RECURSION - Advanced TypeScript made EASY
มุมมอง 1.1K6 หลายเดือนก่อน
MASTERING Type Manipulation in TypeScript Using RECURSION - Advanced TypeScript made EASY
EXTRACT types using RECURSIVE TYPES - Advanced TypeScript made EASY
มุมมอง 8856 หลายเดือนก่อน
EXTRACT types using RECURSIVE TYPES - Advanced TypeScript made EASY
Hey, I know this video is old but maybe this is helpful to someone. On typescript you can use a string interpolation as a type, so this will work also type Email = `${string}@${string}`; const test1: Email = 'testingemail'; // this breaks with an error const test2: Email = 'testing@email'; // this works just fine
what is the extension/plugin/tools that displays the result when using ^?type? this looks very useful
It‘s called „twoslash-queries“ and it also exists for Jetbrains. There it‘s called „witt“
A nice use case for this would be defining JSON schema's which can be used to check JSON documents at compile-time using import. Here's a nice challenge for you: implement types for url's and emails. 😉
This is neat trick but wouldn't use it, pretty sure Typescript checker will degrade pretty quick if code start to be crowded with there kind of tricks. Impressive none the less.
The typechecker is quite good in caching this stuff. But of course only use it if you have a usecase 👍
I don't think it will change the way I work with strings, because most of the strings I work with come from api and are not statically analyzable. But it is definitely a great lesson.
Thank you 🤘, I agree for that purpose it‘s not helpful.
Isn’t this getting outside the domain of types? I don’t understand why you would really want or need this, it is a lot of computation on something that should be a concrete type definition. This is bad practice for typing and I wouldn’t use this code in my code base, it’s also pointed out that runtime checks are necessary for any values that are not a constant.
yep, same! most of the stuff i (or we) deal with are dynamic data (eg: pulling out data from db / api(s)), so you can't leverage this in your projects
Fantastic content and we'll presented!
Thank you 😁
There are no real usage for this
This channel is just super fun! I’m super curious on how you come with these ideas though.
Thank you 😁, I like to fiddle around with the more unusual parts of languages so as soon as you start to do that, the ideas will come naturally 🤘
very cool but as always - please don't actually use it, especially for comparing large numbers; you will kill the compiler and IDE performance quickly
hihi! How do you view the result of the type as a comment like that (3:04)? You were using a different IDE before but not it's finally VSCode I think. Great content btw!
Thank you 🤘. It‘s called „twoslash-queries“ for vscode and „witt“ for Jetbrains.
After watching your last video (which was my first video that i watched from you), i was like "finally, someone who knows more typescript than me". I have read and learned alot from tanners code before. Will binge watch all your videos and read your repos now. Yay. Thanks so much for such content man. The more i watch you, the more i think "man this guy is incredible". This is a simple parser to implement but such a genius idea
Can you explain how to limit a number to range. Currently if I want to restrict a number to be `<=4` I do some thing like `type Range = 1 | 2 | 3 | 4;`. Obviously this is a terrible solution, but I've never found anything better.
you could use tuple types since they have fixed lengths, but i would be against stuff like this in real codebases since its gonna cost a lot of performance (and may error out for excessively deep instantiations)
Counter doesnt need to be an array. It should just be a readonly number
It cant, as we need to update the counter every recursive iteration. Otherwise we would need to create an array and increment it and put it back into a number each time.
Ah yes i just tried and i cant just increment numeric type. Sorry for saying that without confirming it. You are awesome
@ no worries. Thanks for your comment 😁
Think it's better to take string's "length" property directly, as it is readonly despite arrays length property which can be set directly by programmer
In types you can‘t use the length property of the string as it‘s just „string“. That‘s why you need to do that trick.
@@Typed-Rocksthis gives compile time support also. String.length is runtime
Wow this is awesome Subscribed
Awesome, thank you!
it would be great to have possibility to add own error messages :)
We could make it so that instead of never, it returns an object type with an error property in
@@Typed-Rocks but it's not an really error. I mean improvement TS compiler :) but it's just kinda my "ny wish" :D
@@snatvb you might as well make an eslint rule for that lol (assuming smth like this doesnt exist, i am not well versed into the rules)
Wow typescript is so cool and powerful. Maybe it can tell me if func could throw an error, oh wait.
While I see your point, many languages think checked exceptions were a mistake. Often they just get thrown further.
This is the biggest issue in typescript by far
every function can throw an error, a stack overflow or out of memory, checked exceptions are just irritating
you solve typescript types as if you don't know anything else... well done man.
Everyone needs a hobby 😝
Amazing work there. I remember u covered how to make sure rgb values has exactly 3 numbers with template literals. Now I feel like trying with this method to make sure those numbers are within range (0-255).
You could but it could make your types quite recursively deep and not that well readable. So always keep that in mind 🤘👍
I opening a PR with this type first thing monday morning
Keep me updated if they liked it 🤘😁
You never fail to amaze us ! This is wonderful !!!
Thank you so much for your kind words. Glad it is helpful ☺️🤘
I usually prefer to extract extra logic that shouldn't affect the result into its own helper type type Split<T extends string> = T extends `${infer H}${infer Rest}` ? [H, ...SplitStr<Rest>] : [] type Len<T extends string> = Split<T>['length']
you should work with valibot
I will look into it. Looks interesting 👍🤘
As someone whose fairly proficient in C++ templates, wtf over complicated crap am I looking at here?
Just casually drops the plugin of the year like it's nothing. 😂
Glad you like it :)
I’m curious of how the error looks like
I’d rather you fix the outstanding issues on ts-worksheet, than build another extension you might not support…
I am working on it, but many of the issues I can‘t solve. But I will take a look into it
awesome!! 👍👍
Thank you 👍
Type Buddy in the Browser: typed-rocks.github.io/type-buddy/ Plugin: marketplace.visualstudio.com/items?itemName=chwoerz.type-buddy
Hi, the plugin looks so cool, but when i try to run the command Tsw i get: TSX is being installed TSX is installed, tsx is not available in the systems PATH. Please install it. Hope you can help me😅
In which ide are you using it? And in which operating system? And when you run „which tsx“ does it find it?
@@Typed-Rocks lazy nvim (windows terminal), windows 10, it doesnt runs so i don't know if it finds it
Wow This is an instant must have plugin. Thank you very much!
Glad you like it 😁
just a note. writing Find<Inner> or StringOrNever<A> in typebuddy is somehow wrong. you should use normal brackets like Find(Inner) or StringOrNever(A) especially since that is how you define the type itself in your first line. makes no sense to use () there and then use <> later on. bad syntax. beside of that good idea
I think creating d.ts is not ideal since d.ts types are global
I will think about it 👍
This is a minor and stupid nitpick, so feel free to ignore it, but can you add a space between the word "if" and the opening parenthesis? It's triggering my OCD lol
Will add highest priority to fix that 😁
It's done. you can update extension :)
Great plugin! Thanks. Would it be possible to remove de "tb" from the .d.ts filename? Like typebuddy.tb -> typebuddy.d.ts
I will make it configurable :)
Buds, can we all agree thats should work in .ts files without any IDE extensions? I'm thinking of a babel plugin to do it in the background, what do u think?
I've been wondering every time why there's no way to write types like normal functions, and here it is!
You are welcome 🤘. Let me know how if like it.
It looks like this just replaces ternary with if else. So it doesn't fully allow us to write types with functions.
@@EverRusting yes, but if we will use it more and more it could improvements
This is actually a great idea. Will try the web version after my holiday vacation. Question: would it be possible for you to abstract the "infer" syntax with something of your own? Like "getInnerType" or something. I see people always having problems with the "extends" in combination with "infer" all the time.
Let me know what you think about the web version. Currently I‘m not planning in adding „own“ syntax to the functional style as it makes it really hard to have proper syntax highlighting etc
2:26 I'd suggest you to consider "early returns" here as an option. This would make it even easier to understand. You don't really need to use "else" if given option doesn't pass the execution further (which is seemingly always the case here).
Could you give me an example using code? Then I can maybe implement it
@@Typed-Rocks Yes, something like: function Find(A) { if (A extends string | number | boolean) { return StringOrNever<A>; } if (A extends Array<infer Inner>) { return Find<Inner>; } if (A extends Date) { return object; } return never; } function StringOrNever (T) { if (T extends string) { return string; } return never; } Or even more simplified version (however i doubt it withstand more sophisticated cases): function Find(A) { if (A extends string | number | boolean) return StringOrNever<A>; if (A extends Array<infer Inner>) return Find<Inner>; if (A extends Date) return object; return never; } function StringOrNever (T) { if (T extends string) return string; return never; }
@@The14Some1 I prefer the term Guard Clause instead of early return but yeah, I had the exact same suggestion, you were simply quicker. :)
The outfile should probably be .ts not .d.ts
I wanted that it only contains types. Because from the typebuddy file, only types get generated.
@Typed-Rocks Well yeah but you see, even in that case, .d.ts types get treated in a different way and should never be used for actual types in your codebase.
I would even pay to have this plugin for Webstorm too.
I will try my best to create it 🤘
really like the idea. maybe typescript team can add a new keyword "typefunction" which dev can write a type function. typefunction Maybe(T) { if (T extends string) return string; else return T; }
That would be awesome.
Is there a scenario in TS rn where it makes sense to write "type function"? because if not, it seems like a cool idea to just make that a "composite" keyword as it is in this "proposal". It'd fit right in and make so much sense!
This is the kind of type that Microsoft should have created in the beginning, but never did. I like TS but always hated that it can only use nested ternaries to express switch cases. At least with this type buddy, the syntax looks so much cleaner. Thank you so much! 😊
That means much to me 😁👍. Let me know what you think
I was excited when I thought this might enable passing generics without arguments to other generic to use within. I don't really like the if/else chain either, but to each their own there. I think TypeScript would benefit from a terse pattern matching syntax.
I suggested author to replace if/else chain with early returns, which seems always possible to apply to the logic of ternaries.
Amazing thing, a suggestion though, can we write it like this instead: functype Find<T> {} That way it’s more consistant between the definition and the call, and is compatible with the current TypeScript syntax. And can you make a proposal to the TypeScript team to add such a feature to the TypeScript itself?
I don‘t think that the team will approve of it, as it‘s a huge change to the current state. Because of the functype, currently this would stop proper syntax highlighting. But I will look into it
You are a god, thank a lot!
Glad you like it 🤘👍
Definitely a great spell for ts wizard 😂
can this do anything other than if/else branches? variables maybe? switch statements would be cool. because avoiding ternaries by writing a whole meta language just feels like working around the problem instead of fixing it. i understand where youre coming from, ternaries were never meant to be chained a lot, so the problem lies mostly in the language design of typescript itself, tho in that position i would try to reconsider how i write my types, or better yet choose a language with a reasonable type system that wasnt hacked on another without one tbf i have the luck of not being a typescript developer, im sure there are valid reasons youre masochistic
Currently it only allows if else as its really hard to do anything else
Unfortunately I don't think we collectively as the web dev community can just "choose a different language", even if it WAS objectively better than JS/TS. That's sadly not how the ecosystem works anymore. And honestly, TS's type system isn't that bad, you can do some fancy things with it even if it's just if-else branches or foreach mappings. ...just unfortunately it can't do EVERYTHING you'd expect a proper type function syntax to allow you to do. Private type parameters would be kinda like variables, but they don't exist. Default type parameters are too inflexible currently to be used analogous to actual default function parameters. And I'm not even mentioning the many scenarios where one might accidentally say "regular functions can do THIS so type functions should too!" without realizing the domains are probably just too different to offer full parity or even interoperability! I feel like the only real solution for making type functions a thing is for the type system to implement them natively. Just call the user code as a blackbox to produce a type calculation… except I don't think the type checker's inference is that simple, so there may still be unexpected restrictions, or differences in how type functions are "executed". This seems like a NIGHTMARE level problem to solve in general, but damn would it be cool if someone did.