2

I have the following enum:

export enum Categoria {
    Acao = 1,
    Opcao = 2,
    FundoImobiliario = 3,
    ContratoFuturo = 4,
    ETF = 5,
    BDR = 6
}

I use the following code to return the enum members to the screen:

export function enumSelector(objeto: any) {
    return Object.keys(objeto).filter(key => !isNaN(Number(objeto[key])));
}

This enum populates an HTML select. So I select an option and do the post on my form, but what I get is the member name enum. How do I get the enum index? For example: 1 or 2 or 3 etc.

1
  • What exactly are you trying to do here? If you want a mapping from key to value of the enum, you could use the enum directly, possibly without the built-in reverse mapping, like this. But if that's all you want, you probably shouldn't use an enum anyway. What's wrong with just this using a const instead of an enum? Commented Aug 12, 2021 at 2:41

1 Answer 1

1

This code may help you with the issue you are handling (keyof)

enum socialMedia {
Instagram = 1,
Facebook,
Whatsapp,
Snapchat
}
type KeyofEnum = keyof socialMedia;
function getsocialMedia(mediaOfficial: string): socialMedia {
if (mediaOfficial === 'Filters' || mediaOfficial === 'Snaps') {
return socialMedia.Snapchat;
}
}
let mediaType: socialMedia = getsocialMedia('Snaps'); // returns Snapchat
console.log('keyof enum string type Snapchat is', mediaType);

Output:

TypeScript keyof Enum 1
Sign up to request clarification or add additional context in comments.

1 Comment

I don't see how this addresses the question as asked. And keyof socialMedia is equivalent to "toString" | "toFixed" | "toExponential" | "toPrecision" | "valueOf" | "toLocaleString", which is unlikely to be anything anyone wants. Could you elaborate about what you are doing and how it is intended to apply as an answer?

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.