1

I do not know typescript and I have not found any information anywhere, is such a construction possible?

export enum Something {
    'qwe' = 1,
    'rty' = 2,
    'uio' = 3,
}
1
  • You can use computed property names for this: ['qwe'] = 1, ['rty'] = 2, ['uio'] = 3,. But this is exactly the same as qwe = 1, rty = 2, uio = 3. Commented Feb 1, 2022 at 1:42

1 Answer 1

2

If your goal is to have an enum, just drop the quotes.

enum Something {
  qwe = 1,
  rty = 2,
  uio = 3,
}

If you want to use literal strings, you can just declare a type

type Something = 'qwe' | 'rty' | 'uio';

If you want the strings and their associations to integers, you can declare an object and then use keyof.

const Something = {
  qwe: 1,
  rty: 2,
  uio: 3,
}

type Something = keyof typeof Something;

This uses declaration merging, so the two Something names we declare are in distinct namespaces. The type Something is defined in terms of the value Something.

Now Something is a type whose value is any string key in the value Something, and we can write Something[x] to convert a value of that type (again, a string) into the corresponding number.

If you're writing new Typescript code, I recommend just going with the enum and dropping the quotation marks; it's what enum is for. But if you have an existing code base that already does it with strings, then the latter approaches can be useful.

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.