Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: declare a type in .d.ts file and use it without importing

Tags:

typescript

I want to know what is the right way to use types or interfaces without directly importing them (if that's an ok idea).

Currently I have this code:

import { TCollection } from "../__types__";

function doSomething(collection: TCollection) {
  // ...
}

So to get rid of an import statement I have tried to replace typeRoots inside of tsconfig.json with this value:

{
  "compilerOptions": {
    ...
    "typeRoots": ["./src/__types__/types.d.ts", "./node_modules/@types"],
  }
}

And declared a type in ./src/__types__/types.d.ts:

declare type TCollection = {
  ...
};

But still having an error:

function doSomething(collection: TCollection) {
                                 ^^^^^^^^^^^
                                 Cannot find name 'TCollection'.ts(2304)
}

Did I made a mistake or is it an IDE bug or something? Thanks

like image 517
streletss Avatar asked Oct 18 '25 19:10

streletss


1 Answers

you can define the types on the global scope:

// global-types.d.ts
import { Something } from "somewhere";

declare global {
  interface TCollection {
    ...
  }
}

if you do not need to import anything in your global-types.d.ts you can just declare the interface directly:

// global-types.d.ts

interface TCollection {
  ...
}

no need for any tsconfig changes

like image 189
DoronG Avatar answered Oct 20 '25 09:10

DoronG