1

I want to make my TypeScript Enums global so I don't need to import them across my application.

What I have so far:

read-state.enum.ts

export enum ReadState {
    Unread = 4000,
    Read = 4001
}

enums.ts

import { ReadState } from './read-state.enum';

const enums = {
    ReadState
}

global['Enums'] = enums;

declare var Enums: typeof enums;

Then in index.ts

import './enums'; // do this once to initialize enums

var _enums = Enums; // [ts] Cannot find name 'Enums'.

While at runtime this might work, I'm not able to reference the enums through the declare var Enums: typeof enums; because the file is a module.

How can I reference this type definition without importing the module while keeping future enum definitions in separate files?

UPDATE: I also need to set the return type of a function to be the ReadState enum.

Based on the current selected answer I have this:

import { ReadState } from './read-state.enum';

const enums = {
  ReadState: ReadState
}

declare global {
  const Enums: typeof enums;
}

In another file I would like to set the return type on these functions but TypeScript is unhappy:

function getState1(): Enums.ReadState {
  return Enums.ReadState.Unread;
}

function getState2(): typeof Enums.ReadState {
  return Enums.ReadState.Read;
}

1 Answer 1

2

Use a declare global block:

declare global {
    const Enums: typeof enums;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks Ryan.
I've added more to my question. I'm having trouble w/ function return types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.