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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.