0

just a simple question because I don't understand how to do that.

I'm aware of what the official documentation says:

Instead of editing next-env.d.ts, you can include additional types by adding a new file e.g. additional.d.ts and then referencing it in the include array in your tsconfig.json.

So:

  • I create a file named "env.d.ts" and write:
type React from "react"
// it won't work with "declare type ..." nor "export type ..." etc.
  • I edit tsconfig.json
{
  "include": ["next-env.d.ts", "env.d.ts", "**/*.ts", "**/*.tsx"]
}

My goal is to declare types globally for my app. I gave the example of "React" because when I create a component in a .tsx file, I write it that way:

const MyComponent: React.FC = () => {};

My IDE wants me to write "import type React from 'react'". I want to avoid doing this on all the files.

ThomasG2201
  • 676
  • 6
  • 25
  • You seem to be trying to globally declare the type `React` from `"react"`. Why are you trying to do that? It wouldn't mean you didn't need to import React into modules in order to use it. (After all, the type is just the type, not the object with methods on it.) This sounds like it may be an [X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – T.J. Crowder Jun 26 '22 at 12:37
  • on external components, my IDE says I should import "React" when used in a .tsx file. Example: in `Logo.tsx` I create a component: `const Logo: React.FC = () => {};` – ThomasG2201 Jun 26 '22 at 12:58
  • 1
    Yes, you should. Including the type for React in a global `.d.ts` file won't change that. – T.J. Crowder Jun 26 '22 at 12:59
  • This is not only for "React", but for other types too, interfaces etc. – ThomasG2201 Jun 26 '22 at 13:00
  • The point is that you don't just need types, you need the runtime part to, which you get by importing it as you need it. – T.J. Crowder Jun 26 '22 at 13:00
  • How would I declare types globally then? – ThomasG2201 Jun 26 '22 at 13:05
  • 1
    Again, doing that (by itself) will not help you. The purpose of `.d.ts` files is to define types for things that are **already** globals (for instance, things provided by the environment). But you declare global types using `.d.ts` files. [This question's answers](https://stackoverflow.com/questions/39040108/import-class-in-definition-file-d-ts) explains how to import types for use in a `.d.ts` file (you'd have to pair that with loading React globally), but **the normal and correct thing to do** is `import` in each file where you use something. – T.J. Crowder Jun 26 '22 at 13:10

0 Answers0