Does ts-reset fix TypeScript?
Вставка
- Опубліковано 20 лют 2023
- I might have fixed TypeScript - or at least, fixed the things I hate most about it - with a library called ts-reset.
Yes, that tweet in the thumbnail is real: / 1627713574553387025
Repo: github.com/total-typescript/t...
Become a TypeScript Wizard with Matt's beginners TypeScript Course:
www.totaltypescript.com/tutor...
Follow Matt on Twitter
/ mattpocockuk - Наука та технологія
They could always add as an option in the tsconfig to opt-in rather than as a baseline
Add stricter mode
@@echoptic775 Or even an option that forces unkown instead of any to these cases pointed out by Matt's video.
I Believe that would help keep legacy mode with the option to be type safer.
@@echoptic775 Or "strict": "5.1", to let the maximum strictness expand over time without breaking backwards compatibility. "strict": true would just start you at "5.0".
The Boolean filter keeping falsy values in the type def kills me, this is amazing and will definitely be appreciated by my team
If you can't use ts-reset, another way to filter arrays with proper type inference is to use .flatMap instead of .filter
const arr = ["a", "b", "c", undefined];
// arr: (string | undefined)[]
const filteredArr = arr.flatMap(item => item ? [item] : [])
// filteredArr: string[]
please dont die
@@chrisvouga8832 If you pass a function with the return type containing 'is' you can achieve the same result
@@chrisvouga8832 You'd have to tweak that conditional a bit if empty strings are allowed.
as @82TheKnocKY mentioned - you can use type predicate to achieve same effect
I'm scared to see how many errors will pop up after I install this, which also makes me excited to use it 😂 You know you're a TS programmer when you're happy to see red squiggles in your editor. "Ahhhh yes... type safety!"
You’ve presented the concept and examples really well, great work!
Doing gods work 🙏
I like this. Being the tech lead for a big international company, I'm about to start implementing TS for our primary business software together with Svelte. It's going to be added, for sure! Thanks!
That's sooo awesome and ingenious, really cool work !
This is great! I was surprised that you nailed 2 examples that I've tried to deal with multiple times lol
This is amazing! Thank you for this library!
Wild, saw ts-reset on the TL;DR newsletter, no idea it was from this fine gentleman. Keep on rocking!
This is cool Matt. Thanks!
Matt, youre the biggest *gigachad* over here and there, lovely work buddy!
You had me at "Hello"
I am so psyched! 😊
This is really helpful library. Thanks.
Really cool, nice work Matt.
Found a few spots in my API where I was missing guard statements.
Love that it only needs to be imported once ❤
This is skyrocketing! Maybe because it's a skyrocket? This is huge, thanks so much for this!
I love this! you are a life saver ❤
love this filter one
I still believe you fixed TypeScript by doing this. You are a genius Mattie 🎉
Actually … I today had an, let say „augment“ with typescript for not correctly typing a filtered array, removing all null values. That exactly what you showed as your favourite example. I know what I’ll check out tomorrow at work and see what else it helps me there :)
Best clickbait ever.
I was wondering if this lib can include some utility types which are not included in TS, like “AwaitedReturnTypeany> = Awaited“ and “Exact = {[K in keyof T]: K[T]}“
Sounds like it would belong best in a different lib!
that's it
finally i don't need to typecast my filtered array anymore
oh thank you for making this lib!!
Cool Explanation!
Mate… You are amazing!
coming from PHP, where the @organization is mandatory (on composer), I find it great! this way it's easier to check the provenance of a package without digging through npm, adding a layer of safety and maybe even accountability.
When things are open source and you can pin the versions, don't know why this matters. Smells of audits and bureaucracy. I understand ISO/SOC, but I also understand I have precious little time and need to work on the most valuable thing and ship value to customers. And audits get in the way of that, so I try to do the bare minimum and automate as much as possible @ work so it's minimal pain once a year.
@@seannewell397 I don't know how you went from naming conventions to audits. Maybe I wasn't so clear in my point? I only said that Composer (npm for php) uses a two-part naming system, so you always know what is the person or organization behind a package. Typing "@react/react" or "@facebook/react" is slower than typing "react", but not by much…
I love this!
For 'any' I typically rely on eslint no-unsafe-* rules so that is normally not an issue for me. Filtering collections and having the correct collection type is a great thing. However I'm not sure I would like to include an additional package just for that. Great work in any case.
hehe same, although this "package" is literally only some type definitions for development ergonomics, does not affect actual running code at all
Agree - though I think this solution would run faster because it doesn't rely on re-running/re-querying tsserver. So if you're noticing a slowdown using the no-unsafe-* rules, this might be a useful alternative.
Cool, I will check in my project
You released this today and it has 1.8k stars in Github? Legend!
The Array filter typing 🤩
I'd love to see a revised version of the normal libs, or some related flag, that revises all the places where any was used before unknown was added to the language.
It also seems this might work as a types library (except for that annoying behavior that specifying types at all removes the default behavior).
It just seems to be this is more a compiler targeted library than a "include this in your code" library.
MS devs are trembling at the TS wizard's power
Wow, that's super interesting!!
The filter bit would be very helpful, this is a very common issue for me
I've started applying zod schemas around my JSON.parse calls so what comes out is parsed, validated and typed all at once.
True TS wizard at working 🧙♂️
Yes!! Just YES!
Wow you are really a typescript wizard 👍👍
If I want to buy your Total Typescript course for my team at work, do you have some sort of bulk discount if I buy a certain number of licenses?
oh, if it only needs to be imported once I'm definitely adding it tomorrow!!!
Will TS be understood by the engines like V8 ( and the browser ) in the future ?
I really like the changes. Personally, I am not sure it includes enough to warrant a full package and would maybe rather a copy/paste approach but that may just be due to me already having an ungodly amount of dependencies to manage already
hell yeah the deps section of mine is almost the size of the screen...
This is a dev dependency, though. It won't get bundled into your code so it doesn't really matter how many of those you have. Copying and pasting is still creating a dependency, it's just doing it locally and means you won't have the option to update it via your package manager when new changes come out.
@@soviut303 it doesn’t really matter how many isn’t exactly true though is it even if they are dev dependencies. Especially when working on large codebases there is definitely a cost on how many packages you have to manage, upgrade, etc. also, your point about still creating a dependency by copy/pasting I don’t really understand, it’s no more a dependency than other LOC in your project reality.
@@adamwheatley3372 Dependencies come with documentation, tests and escape hatches. Code someone randomly copied into a project usually has none of those things and is now embedded with no support once that person leaves. You're now stuck with legacy code that you have to maintain, which is one more perpetual distraction from the actual problem your software is supposed to be solving.
@@soviut303 my whole point was that the code in this package doesn’t warrant a full package. These types don’t have tests, document themselves, and don’t require an escape hatch. Your argument is basically all code is legacy code if it’s not in a dependency, sadly in real life you need code!
2:34 OMG!!!!! Thank you!!!
How did you make it so just importing once it expands to the whole project?
I personally prefer the org namespace on the module import.
Any chance you can fix the "Property x does not exist on type EventTarget" error? 😊
Can you add the Object keys to be (keyof Obj)[] instead of string[]? And also the object entries
Nope! Check the readme for why
@@mattpocockuk I see, it is a good point.
Hi, @Matt Pocock
Could you please take a look on a library I've been working with these last months?
It's called ts-narrow, documentation is kinda bad for now, but you can have a pretty good idea on how it works from the unit tests inside it.
Thank you for your attention anyways!
Dear sir, I love your contents. Thank you so much.
I wonder about the "is-array" rule, instead of unknown[] wouldn't ReadonlyArray be a better type fix? It seems otherwise mutable methods such as push, that were prohibited by the type declaration, would be allowed again.
Cool lib!
What about just eslint no implicit any?
2:25 - Yes! This little thing has been buggin me for some time. Thanks :p
NPM Organisations should be mandatory. Over the years so many NPM packages have just died or the maintainers have given up. Having all packages scoped to an organisation makes forking a project have much less friction.
As it stands, the "global" packages (for the lack of the better word) will always take precedence in the minds of developers.
Filter is a good start, can you make it work for reduce too?
What problems are you experiencing?
when you type "// ^?" a type hint appears on the screen. What is that? is it an extension?
♥
❤ Great! I probbably should be sleeping right now (greetings from Prague; 3:41AM) BUT I have discovered this project and must include into my projects.
what's the extention that's showing types?
ua-cam.com/video/u0adKDu--cA/v-deo.html
Is there a way to get the "// ^?" in VS Code by any chance? It would be amazing
www.mattpocock.com/faqs
Would there be any downsides regarding performance? I guess for the JSON parse you're just changing the return type but not sure how the filter is actually done
I don't think so - for many of these I'm simply adding another overload, which is easy for TS to match.
1:01 😮 ….. nervously looking at codebase
also test utils in ts-reset repo are interesting… some of them could be included in TS, for example Expect
Looked at the repo - and to clarify, if you add interface definitions with differing signatures, it adds overloads to the original definition?
Correct!
Already saw it passing by on gh and ✨ it. Great project 👍 It's a bit scary it changes the global types, reminiscent of monkeypatching, but since the changes are conservative I am fine with it? Kinda hope (at least some of) ur changes could be upstreamed, because they just more accurately describe the types imo. I sort of assume that array.filter would be too heavy on performance to have it in official ts, but things like the JSON parsing to unknown instead of any just feels right and shouldn't have any impact.
now this is poggers
Are you using an extension to see the actual type in the comment line?
I think I'd love having a generic that defaults to unknown, so if I know the json I'm parsing (or have error boundaries to catch stuff) I can just get the type attached right away without zod. What really badly needs fixing tho are the static Object methods. What good is string[] as the return value for Object.keys for Records of specific keys. Keep having to manually type those, defeats the entire purpose of using TypeScript moreso than what I do with readFileJson and readFileYaml...
Object.keys is explained in the GitHub page of ts-reset. To paraphrase: ts does structural typing, meaning that an interface/type can describe the key-values that HAS to be in the object, but it can not describe the type that SHOULD NOT be in the object. A union of strings on the other hand, does describe all the possible strings that are valid. So Object.keys could return more strings then the keys of the type/interface that is describing the object, and it would still be considered 'correctly typed'. Hope this makes sense.
The best!!!
God that's great
Always snag the npm namespace first, ask questions later ;) I even made a package that does just that (hold-place).
Also a suggestion, I would personally be more likely to use this if it were vended as a plugin/extension system rather than the all-or-nothing approach. It's hard to justify bringing it some external code that will fundamentally alter the behaviour of TS unless each modification is explicitly declared.
This is neat, I'm gonna have to give it a try. At first I thought it was doing the same as noImplicitAny in tsconfig, but that's different since things like JSON.parse explicitly return any, even if you don't notice it.
Here we go :D
I have been waiting for the typesafe filter function all my life, super annoying that TS can't infer it by itself
Is it possible to have it in an Library and dont ship it in the bundle?
It would be interesting if there were a way to do this more generally, not just in one-off situations. For instance axios returns any by default too, unless you manually specify the generic. I don't know of a good way to wield the ts compiler or eslint to do this unfortunately.
It seems though that banning assigning the result of a function call to any without a type annotation might get us a long way. Or perhaps there could just be a TS option that makes any function returning any return unknown instead.
Banning any altogether seems misguided, but the cases where you silently get any as a result of a third party function call seem generally pretty harmful.
1:16 hmm what about «parse, don’t validate»?
What tool are you using to get those comment previews of your types with "^?"
I'm also interested...
It's a feature of Typescript Playground. But i use vscode-twoslash-queries extension 🙂
@@kevingeorget6002 thanks! This is a life saver!
Awesome! Great tool for developers so safeguard their development.
Is the "^?" To display type annotations a default os VS Code or is it from an extension?
www.mattpocock.com/faqs
@@mattpocockuk ty!
new sub thanks to primigen
Could you disable all global imports? 😬
a reset for window would be amazing, now days a lot of code is server render, where window is "undefined" yet when you write the code the IDE always pops the error where window can not be undefined when you do the classical if(window===undefined)
I usually do `typeof window !== "undefined"` to check that I'm running in the client
i do not use ts or js, btw it is really cool changes for production
can someone explain to me, how those comments '^?' work in vscode? Is this an extension?
www.mattpocock.com/faqs
@@mattpocockuk thanks mate!
Can someone tell me how he is getting the type of that particular variable autofilled? with the // ^? comment? Is this copilot? For me it just gives a random comment.
ua-cam.com/video/u0adKDu--cA/v-deo.html
i am afraid to do this as an experiment in my project...
This is awesome, and can’t wait to use this!
Btw, how’s it going to be used inside real world apps like NextJS repos, and what do you recommend?
Import inside _document.tsx, inside next.config.js, or somewhere else?
Anywhere! Doesn't matter a jot.
@@mattpocockuk That's great! Though, where do you suggest it to be used in Next.js, so that it won't matter even if the project structure is changed significantly?
@@Just_Moh_it Won't matter at all! _app or _document feel natural.
This is so cool but is there a way to automatically import this in all typescript files?
Yes, a single import will make it go through the entire codebase.
@@mattpocockuk So it covers global types even for tsx files etc? thats cool so its like overwritting the global types, lovely!
Nice job!!!
Is it possible to fix the Object.keys to be more type safe? :D
Example:
const a = { aa: 1, bb: 2, cc: 3 } as const;
const values = Object.values(a); // (1 | 2 | 3)[]
const keys = Object.keys(a); // string[] expected: ("aa" | "bb" | "cc")[]
Take a look at the readme!
Matt will be live coding in 10 minutes guys!
thanks, these were the 2 things that bother me the most
why not add it to tsconfig as plugin?
Because plugins don't contribute to typechecking.
HELL YEAH I FOUND IT AGAIN
That was good clickbait.
YES
What's the plugin that shows the type in your comment
mattpocock.com/faqs
@@mattpocockuk gigachad
How is this different from using typescript in strict mode and using the noImplicitAny flag?
All of my examples show TypeScript in strict mode, including the ones with any's coming from JSON.parse.
Shouldn't a library be able to opt-in in an isolated way for itself? Might be difficult to implement but could be nice. I find it's a bit limiting to opt-in at an "application level" as I think library boundaries can be quite arbitrary, for example, in a team, someone may opt-in but then wants to move their code to a library for another part of the team, and then this part of the team doesn't want to opt-in for their part of the code. So I think the global opt-in is a bit limiting, but I'd imagine it would be very challenging to implement isolated opt-in.
Great