1

I am trying to declare ts type globally. I have sth like this type Nullable<T> = T | null which is used in project files. I dont want to copy this part in each file. I tried to declare this type in declarations.ts or declarations.d.ts like this declare type Nullable<T> = T | null, my IDE and compiler is OK with this but when I use this project as a module (import) in another project, then I get an error: Cannot find name 'Nullable' in d.ts files.

Can you help me how can I declare this generic type globally? Do you have any ideas? Thank you for response.

stefanprokopdev
  • 333
  • 2
  • 12

2 Answers2

2

You can declare the type in global to make the type globally accessible without any import.

declare global {
    type Nullable<T> = T | null
}

Note As with anything in a global namespace you will run the risk of name conflicts with other modules.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

Not sure what you are trying to do, but you could use exports:

// lib.ts
export type Nullable<T> = T | null;

// main.ts
import { Nullable } from "./lib.ts";

let a: Nullable = null;

Of course you'd still have to add an import statement at the top of every file.

J Winnie
  • 153
  • 1
  • 8