Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global types in typescript

Is there a way to make a file in your typescript file that defines globally accessible types?

I like typescript but find that when i want to be truly type safe I have to explicitly import types from all over the system. It's rather annoying.

like image 320
Tal Avatar asked Mar 23 '17 19:03

Tal


People also ask

How do I use global TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.

Where do you declare global type variables?

In Python and MATLAB a global variable can be declared anywhere with the global keyword. Ruby's global variables are distinguished by a ' $ ' sigil.

What does declare global mean?

declare global is used inside a file that has import or export to declare things in the global scope. This is necessary in files that contain import or export since such files are considered modules, and anything declared in a module is in the module scope.


2 Answers

Yes this is possible. You can find all information here: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html

The important part is this:

declare global {     /*~ Here, declare things that go in the global namespace, or augment      *~ existing declarations in the global namespace      */     interface String {         fancyFormat(opts: StringFormatOptions): string;     } } 
like image 53
Sebastian Sebald Avatar answered Oct 09 '22 03:10

Sebastian Sebald


I found the accepted answer is not working (maybe it is some configuration that needs to be done?). So with some tinkering, I got it to work for me (maybe I also have some weird configuration option? Let me know if it doesn't work and I will remove this answer).

  1. Create a definition file in a suitable folder. I will be using types/global.d.ts
  2. Check your tsconfig.json and include "*": ["types/*.d.ts"] under paths. (You should also be able to directly address the created file if you care to).
  3. Put your global definitions directly into the root of the file NO declare global or similar.

Now you should be good to go to use the types declared in this file (tested with typescript 3.9.6 and 3.7.5).

Example file:

// global.d.ts declare interface Foo {     bar: string;     fooBar: string; } 

What your tsconfig should look like:

[...] "paths": {     "*": ["types/*.d.ts"] }, [...] 
like image 32
Elias Avatar answered Oct 09 '22 04:10

Elias