2

I want to provide an interface that guarantees that an enum definition will be passed.

// msg.ts, here's an example enum
export enum Messages {
  A,
  B
}

// interfaces.d.ts
export interface IThingy {
  Messages: Messages
  // ^ how do I specify that Messages should be the actual, full enum, not a member of the enum?
}

I want consumers to be able to access that enum as though it were injected. For example:

function (param: IThingy) {
   param.Messages.A // ok!
}

If that's not possible, how could I feasibly achieve the same effect? Ultimately I just want to pass around a constant, strongly typed K:V (string:string) map.

I did see similar: Enum as Parameter in typescript, although my intent is sufficiently different.

cdaringe
  • 1,274
  • 2
  • 15
  • 33

1 Answers1

2

Well, you can do it exactly like that:

export enum Messages {
  A,
  B
}

function fn(param: typeof Messages) {
  console.log(param.A); // ok!
}

fn(Messages);
fn(string); // no
// although, due to Structural typing:
fn({A: 0, B: 1}); // works!

Though of course, I'm not sure about the purpose of this. If you're passing a concrete enum, you don't exactly need to pass it, as you could refer to it by its name. What you can't do is to create a function that accepts any enum and only enums, as the question you reference points out.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42