0

We've defined some enum values in a const in our codebase, like this:

const Templates = {
    NewMessageFromBot: 'new_message_from_bot,
    NewMessageFromHuman: 'new_message_from_human',
    NewUnreadNotification: 'new_unread_notification',
}

(Example is shortened intentionally, but does in fact contain almost 100 entries for our different HTML templates for messages.).

We want to use these names as typings for a function like

function getTemplateName(message: MessageDocument, templateName: Templates) { ... }

But of course we get Templates' refers to a value, but is being used as a type here.ts(2749)

Is there any way to reuse the Templates object as a type, or do I need to refactor it to be an Enum or does anyone have any good suggestions? Thanks in advance!

I've tried searching for similar topics, by searching for "reuse objects as types in TypeScript" but it does in fact seem I need to do something advanced here, or just refactor.

function getTemplateName(message: MessageDocument, templateName: Templates) { ... }
1
  • 1
    typeof Templates will give you the type of any const value enjoy. Commented Apr 23, 2019 at 22:50

1 Answer 1

1

You can use String Enums, the solution would be:

enum Templates = {
    NewMessageFromBot = 'new_message_from_bot,
    NewMessageFromHuman = 'new_message_from_human',
    NewUnreadNotification = 'new_unread_notification',
}

You may use the Enum as type, and also get the string.

Here is some info about enum, in case you want to take a look.

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.