Geir Sagberg
Geir Sagberg

Reputation: 9821

Is it possible to share global declarations in TypeScript?

I usually have some server-side variables that I put into the global scope, so that I can access them from anywhere in my client side TypeScript code, e.g.:

Server in .cshtml:

<script>
  const RazorGlobals = {
    apiBaseUrl: '@Model.ApiBaseUrl'
  }
</script>

Client code:

declare const RazorGlobals: {
  apiBaseUrl: string
}

fetch(RazorGlobals.apiBaseUrl + '/myResource').then(doStuff)

At the moment I have to repeat the declare const RazorGlobals... part at the top of every file where I need to use it. I am looking for a way to define this declaration in a single place, something like this pseudocode:

globals.d.ts:

export declare const RazorGlobals: {
  apiBaseUrl: string
}

file1.ts:

import './globals'

fetch(RazorGlobals.apiBaseUrl + '/myResource').then(doStuff)

file2.ts:

import './globals'

fetch(RazorGlobals.apiBaseUrl + '/myOtherResource').then(doOtherStuff)

Is there a way to achieve something like this?

Upvotes: 3

Views: 4748

Answers (2)

gilamran
gilamran

Reputation: 7294

First, don't assume global variables, there are many reasons for that.

You can have a module in the client that exposes these types, this module should take the global variable and expose it.

For example

config.ts

import { IAppConfig } from '../shared/AppConfig';
export const APP_CONFIG: IAppConfig = (window as any).RazorGlobals;

component.ts

import { APP_CONFIG } from './config';
console.log(APP_CONFIG.apiBaseUrl);

As for sharing types, you should have a shared folder between the client and server, and all the types should be there, in this example AppConfig.d.ts

Compiling the client AND the server with the same tsconfig.json is very problematic. I have a medium post on that, and an open source starter-kit.

Upvotes: 3

toskv
toskv

Reputation: 31600

If you want to declare the presence of a global variable that is available everywhere all you need to is have a .d.ts file with the declaration in it.

// globals.d.ts
declare const RazorGlobals: {
  apiBaseUrl: string
}

No imports should be necessary.

Upvotes: 5

Related Questions