TypeScript doesn't support this pattern: github.com/mic... Become a TypeScript Wizard with my free beginners TypeScript Course: www.totaltypes... Follow Matt on Twitter / mattpocockuk Join the Discord: mattpocock.com...
You pre-empted me and my commenting, you rascal! 😉 Tbh though, whatever you've got going could work just fine as long as you eliminate the echo. That is to say, sound treating the room.
I think folks do it cuz: 1) The ".d" part of the filename makes it seems like it's where you should define types or something 2) When you open any library "d.ts" file and you'll see that it's a file full of type definitions, one can get the impression that "d.ts" files are simply files where you define types you wanna use across your project (not saying that's right, just describing the impression i had had)
That's why I generally don't like 90% of the web devs I've encountered: they assume lots of stuff and usually think others are in the wrong, not them. Web devs are the forever wanna be devs, not putting enough work to understand their flaws and wanting others to bend to their flawed necessities. And I'm a web dev.
This explanation pretty much put you on main part of normal distribution where on the left side there's a noob and other side senior, saying "it works, don't care".
I prefer separating types into different files inside a "types" folder that contain types for specific things (like database types in one file, utility types in other file and some app stuff in 3rd file), I don't like the approach of putting every single type into 1 file bc especially in large applications we end up with a huge and hard to maintain types file. Also, I put types into types files only if I have to use them somewhere else, otherwise I would just define a type right in the file that will use that type
I think all depends on the scope of the project and it's nature. If it's big one with hundreds of PR's and thousands types defined having a giant single file would be ridiculous 😂 in my experience the best is a mix. If you have some types u use Everywhere - use them in global scope. If you have types you use only where you defined it or use them somewhere else where you import it - use them within the file. If you have complex use case where some interfaces are shared, some are used separately - create one file if that benefit the clarity. Also worth to discuss these as you go with your teammates to make sure that you all following the same patterns and that you all agree. But this actually should be a part of Code Review and initial phase of a project
I do the same and for the first time I disagree with Matt on this one. If you put the types in a file co-located with the items using it (sometimes to solve circular references) and don't make it a definition file then you will now have an empty module output. I usually put the types in the same file but sometimes they need to be separated out for readability of the code it's typing for the other Devs in the team. I do agree there should never be actual code in a .d.ts file but then doing that had never even occurred to me.
Yup, I type stuff coming from APIs in d.ts files because they are global and are passed around through components. Seems like the correct way to do it so I am not having to redefine types every time I use them.
At 1:20 Let me show you exactly why they're so bad... But a straight up answer never comes (only indirectly)... So I think I understand, but the explanatation doesn't go into why declaring types globally is a bad idea. And why can packages use them for sure, but you shouldn't as module declaration files... Still unclear to me. 😊
I use .d.ts to augment some types and interfaces of the external libraries. Example: there is a leaflet map library, and there are a bunch of plugins that are written in pure js, but they add to the library's inbuilt features. So to make typescript happy, I declare those types there.
I have an answer to your question: Why do people use them? I can answer anecdotally with my experience: because ts docs are a mess, and you didn't yet made an explaination video about it. 2 takeaways: - ts docs should be rewritten from scratch - you are a rare gem, thanks for existing ❤
so if you wanted to make a package that was just a type definition to publish on npm, for example an AnyStringWithAutocomplete (that weird "| (string & {})" or something like that, you just have a .ts file instead of a .d.ts file?
I used to write .d.ts files for ambient type suggestions via jsdoc before we took the time to swap to typescript's actual runtimes. It was a big project and it took a while to have the time to do the migration.
I think it’s fine to have a “types” or “models” folder, as long as it’s one type per file. If I have a User model, that’s gonna be used in many places, so it should in a central, shared location. Otherwise you’re either going to be redeclaring it in various files, or potentially importing the “User” type from some unrelated component.
Putting my internal types into a global.d.ts file caused me a lot of headaches to actually get it to work and then realize that this approach was completely stupid. Not only because Typescript interprets two different types of declaration files (one with imports and one without), but also because it's very cumbersome since you have to re-type all the used internal classes because of the type-value difference. I learned that you should not use declaration files if the compiler does not complain about missing types from external modules or unknown imported file types it cannot read.
All my projects have an index.d.ts in the project root where I augment libraries, like adding properties to the express req object, for typing process.env and adding semantic alises like type IsoDate = string or type UnixTimestamp = number.
I’ve been using TS because of ReactNative for years but it is only now that I’m realizing how much separate TS knowledge I need. I’m learning so much from your channel. Thank you the breakdowns!
I mean, we are talking about a superset of features (because Typescript really isn’t a language) that was designed to make a scripting language do something it wasn’t designed to do. And the bandage keeps getting bigger and bigger.
A huge smile spread on my face when i read the title of this video. About a year and a half ago i started my first frontend dev job, and on my very first task, on the very first week, i stumbled upon our app's huge usage of the .d.ts files. I tried asking several of my peers what is this ".d.ts" file, and nobody knew, one assumed that the "d" stands for "deprecated" (to which i replied in a question - "so why did you declare new types in a new .d.ts file just two weeks ago?"). So i did a bit of investigation and soon enough i understood the depth of the antipattern that is spread all over. You see, i came from Python, and in Python, as Python is, it is extremely easy to make a huge mess and chaotic code, because no typing is required. So i was very sensitive to this issue. So at the end of this first week, and actually up until today, because this thing is like cancer, my crusade is to get rid of all our .d.ts files. Good luck to me.
Found this out the hard way a while ago. Now I only use .d.ts files to declare certain modules I need to have globally available. For example, if I'm using SCSS modules, Typescript normally doesn't know or understand what they are so I declare them in my types.d.ts as declare module "*.module.scss" { const content: { [className: string]: string }; export default content; } I suppose this is what it was meant for
I think you have to reevaluate your sentence. That you dont do it when you write Typescript. But for JavaScript, you can do it. If you generate JavaScript from your Typescript code, or just writing JavaScript itself. you have a prejudice that everyone writes Typescript. Maybe it is your preference, but not for everybody. At the end, if you write Typescript or JavaScript, your production code is JavaScript (your application and npm package), with our without d.ts files. I think you only prefer to write Typescript, and dont want to write the d.ts itself by hand.
I agree with you but then, I was wondering why npm suggests you to create a `.d.ts` file when it could have just told you to have types files ? N.B. : I am currently creating a React npm package and I just saw the npm message...
I still dont understand the issue. I use d.ts files to make my types global so I don't have to import them into every file. What if every time I wanted to use "let" or "const", I had to import it? That would get annoying. So for certain other common fundamental types in my app, I put them in a d.ts file. Is that blasphemy?
Thanks, that exactly that info i want. I wondered why I shouldn’t store all my types and interfaces in d.ts, because it looked convenient - I don’t have to import them. But I suspected there was a catch somewhere...
Thanks for the revelation, Matt. I think I do this because types feel like such a specific feature of a codebase to me that it doesn't make sense for type declarations to be modular inherently. It made more sense in my head for them to be global; if TS doesn't end up in the bundle anyway, why should I care about the import statements? That's just how I thought about it, but never thought that it could be an issue.
Bad technology where people have to struggle with the question where their types go to ;-) Don't understand me wrong, TypeScript is the best thing which could happen to JS. But JS itself is horror and deserves to be forbidden :P
Hi Matt, thanks for this! Very interesting. About skipLibCheck, I thought it was about all the typings, not just custom ones. But why disabling it? I mean, wouldn't it be better to have it disabled ("false") so TS warn you are making code-smell? Would it be perhaps be better to have a tsconfig.build.json file that turns it true while on development it is turned to false? I'm used to always create two tsconfig files, one for build and one for development. What's your suggestion here? Do you agree with this way of making ts projects? Thanks!
@@mattpocockuk I make tsconfig.json to extend tsconfig.build.json, so what's really important stands in production file while things like "paths" stays in the dev
After seeing tons of garbage typescript definition file all over the place from different projects time to time, where you have to constantly jump between different files to check out and correct the typescript. Similar to when you have a big CSS file or multiple CSS files where you constantly have to hop over to check out a specific class style. For 99% of the times and non library development, if there is no hard guideline for the typescript definition across the team, I simply put typescript definition on the top of the same file that is using the typescript if it's not going to be shared anywhere. No import, no export, less typescript confliction during the review, people change it on demand, scope well, move out of scope on demand, no premature "typescript optimization”, works the best. Big file issue? It's always case by case. Big file can be simple if the code flow is clean, small file can be complex if there are tons of unnecessary nested abstractions everywhere. People will thank me later if they don't need to jump between files to figure out a simple logic.
I'm confused here. At one point you say "that's what declaration files are for, putting things in the global scope". Thrn uoubgononnto say "never put types in the global scope". So, why? And what are you supposed to put in declaration files ifnit's.notnthe types you eant to share? If you have types that are used throuout your projectnthen why eould you want to be importing them in every file? And why are you trying to put runtime code in your type declaration files anyway?
How about a video on why 40% of the people do this wrong. Is it bad documentation? Are the profession books teaching this wrong? Did everyone just learn it from some random youtuber?
I use .d.ts to declare some project specific types that I want to use everywhere in the project. That way they got into global scope so I don't need to import them in every single module that uses them. I also use namespaces, so different parts don't clash with each other. What's wrong with that?...
whats interesting is why people use .d.ts in the first place .. as a FE dev we always just used .ts for interfaces ... but the internet kind of suggested otherwise. If it seemed like convention - people will follow. But why did we follow this guide to begin with?
I hate how fastify forces me to make d.ts files and use declaration merging for their interfaces. I spend weeks to setup the tsconfig so my monorepo packages work when being used as a dependency.
I hate .d.ts files because any time you jump to definition it actually jumps to the types. great, i know the types of this function that i have no idea what kt does..
I feel like this is the TypeScript docs's fault. I remember trying to read the docs about .d.ts files and not understanding the use cases for them. The docs do not make this clear.
When i started at my new job i saw this .d.ts file nonsense and well continued the pattern, now i regret my decision 😅 volate your damn types or wirst case have a types folecto share types easily.
Thanks for the information, but I haven't seen the use of .d.ts files in any tutorial project other than declaring types and interfaces. However, if you create a types.d.ts file in the root of the project, you can use types and interfaces without importing them, but just by specifying types (interfaces), which in my opinion is very convenient.
2:40 I think that's wrong. I think that applies to any TypeScript file (ts or d.ts) that is included in a tscofnig (via include array or files array) as long as it doesn't contain any import or export statements. If you use any import or export statement in a d.ts file, types won't be availible globally anymore. At least that how it works for me, don't ask me why. Global types can be useful at times though (for example for some custom helpers like 'UnionToIntersection' or 'DeepPartial').
It's a cool feature, but you will have to be careful naming your types, specially if you're using React, or any other library or framework, because you could be naming a type with a name that already being used by that library/framework, and if you're not paying attention, you could end up choosing the wrong type.
1. When you need to type some JavaScript 2. When you want to make alterations to a global type, like in this article: www.totaltypescript.com/how-to-properly-type-window
i think a better explanation is that it is for compiled ts code that has become js, not for us to write directly so you can have the actual runnable code, and the types for developers to use
Hi @mattpocockuk - I watched the video more than once and I'm confused between the title of it and its content. Can I use an env.d.ts global file in my Astro app for example to declare a type that I know for a fact I'll use throughout my codebase? Is this not recommended?
I think a video demonstrating when you would transition a type from a normal module to a d.ts file would be very helpful. Some kind of simple project where a User type needs to be changed from local to global; something like that.
I think one of the points he's making in the vid is that you shouldn't use .d.ts files for your own types. They're really only used for adding types to js files (like in the case of npm packages) or weird hacky type overrides
I hate how the .d.ts files are often used in Express apps. The request object is given to middleware and the type of its data property is often defined using a .d.ts file. But all of the properties have to marked as possibly null since that's how the request object starts. And then every single middleware function has to type-check that property again for type safety.
That's very helpful to know! Something else I've wondered, is should we put centralize the types, or have them distributed around the codebase. At work, we have a types folder with multiple files for each kind of category like auth.ts, billing.ts, etc. Is that an antipattern?
I sometimes use global types for automatic declaration merging because I need to extend types that I share with my git submodule(s). This means i can share types with my submodule, but also extend these types with project specific stuff. I don't use .d.ts files for this, instead I use "declare global" in normal module files. Before watching your vid, I would have said it doesn't make a difference, but with your skipLibCheck advice, it does actually.
i always have a .d.ts file for my glsl files: declare module "*.glsl" { const value: string export default value } is this the correct way to do this? or should i use plain .ts?
I have a related question that maybe somebody have faced before : If i create a `customTypes.ts` file, where I create and export some interfaces/types, and i put that file inside the folder where I have my `main.ts` file (where I write my code), How could I exclude that file/folder from the compilation? I'd like that the compiler do not create a `customTypes.js` when compiling. I tried to create a ` "exclude":["customTypes.ts"] ` in my `tsconfig.json`. , but since the file contains "export" declarations , the compiler walks through that file anyway. Do you have any standar solution, or a way to really exclude a file with import/export statements ?
What's about things like: declare global { interface Window { /*extends*/ }}? Should it be .d.ts? It's a global thing, not a module? Also, sometimes it's necessary to radicle some module typings: declare module 'universal-router' { /* some magic here */ }. What would you recommend doing in those cases? Thank in advance
Hello Matt, thank you for all these useful videos about TS. I'm currently binge-watching them. I use spatie/typescript-transformer to convert my PHP code to TypeScript (in a Laravel-Vue-Inertia stack). Let's say I have a DTO UserData with name and email as properties, this class then gets transformed into a App.Data.UserData type that's available globally without importing via .d.ts file. For me it's very convenient since I don't need to import these DTO everytime I need them and they are generated automatically (from PHP code). Is that a bad design as well? To me it ressembles all these ".d.ts" that accompany ".js" files like explained in the GitHub post you included in the description box.
I was first confused by the title and then realized that it is about people creating .d.ts files manually. I never thought anyone would work with .d.ts files except for compiling into a package or importing typings :D
Why would I not put my types in a normal module like everybody else? Let's take my latest project as an example, a file server which builds a virtual file system on top of the one provided by the host OS. It supports linux, mac and windows, but they all handle files and file paths differently. That's why I have multiple classes that handle drive partition and folder access for their specific operating systems, but I also need to have an interface they all implement in order to have a consistent and reliable API.
I’m sending this to a department at my company I often butt heads with. They love putting types in a declaration file and I hate it. Put types where they’re used. I didn’t know the typescript team specifically calls this nonsense out. But now I have ammo for why they should stop doing that
What would be the correct approach when building a component library with typescript? ts, tsx files? I've seen d.ts files referenced on the types property of the package.json file
This is what happens when devs jump into codebases with little to no knowledge/context of what they are looking to. They'll try to figure out things doing some "reverse engineering" that may lead to wrong interpretations.