When to use types.ts vs types.d.ts
Asked Answered
F

2

21

There are many resources explaining a declaration file (d.ts) is useful for either:

  • Declaring types for JS libraries used in your TS project, or
  • Allowing your JS library to be consumed by other TS projects

What confuses me is that many projects like material-ui are using d.ts files to simply store types and have them consumed in their own code.

At this point I start questioning, what's the point in having types.ts files where we have to export / import types and interfaces to consume them, when we could have types.d.ts files and simply consume its interfaces / types without the need for exporting / importing? What are the pros and cons of using one over the other?

Fanny answered 11/8, 2021 at 19:7 Comment(0)
R
20

In most cases you should just write typescript files, and let the compiler generate your .d.ts files for you. This is almost always the right choice, except:

  1. For some reason you are not allowed to write typescript, and you must write everything pure javascript.
  2. You are creating or modifying types from another package. .d.ts files can help you override those types.
  3. You have an extremely large codebase.

I imagine Material UI in group 1 for this. Deno is in group 3.

tl;dr: stick to writing typescript. Writing javascript and separate type files is extremely unergonomic and you lose a ton of the benefits of typescript.

Riles answered 11/8, 2021 at 21:54 Comment(0)
R
11

.d.ts

  • To indicate this file should not be compiled
  • Place declaration type and will implemented on js somewhere
  • Only types file

.ts

  • Normal typescript source code
  • Executable code that must compiled
Retinite answered 11/8, 2021 at 19:19 Comment(2)
Thank you Ardy, that's useful! Which one should be used to simply consume types within the project and why would that be the case? What about performances between the two?Fanny
If your project completely using typescript use just use .ts otherwise use .d.ts example your project is library, that let another people which just using javascript and get usefull types from .d.ts fileRetinite

© 2022 - 2024 — McMap. All rights reserved.