3

Let's say I have defined

enum Sort {
  nameAsc = 'nameAsc',
  nameDesc = 'nameDesc'
}

Can I do something like this?

const key = 'name' + 'Desc';
Sort[key]

Thanks in advance

2

1 Answer 1

4

Yes

This:

// index.ts
enum Sort {
    nameAsc = 'nameAscValue',
    nameDesc = 'nameDescValue'
}
const key = 'name'+'Desc';
console.log(Sort[key]);

Compiles to (using tsc index.ts):

// index.js
var Sort;
(function (Sort) {
    Sort["nameAsc"] = "nameAscValue";
    Sort["nameDesc"] = "nameDescValue";
})(Sort || (Sort = {}));
var key = 'name' + 'Desc';
console.log(Sort[key]);

Which outputs (using node index.js):

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

1 Comment

It only compiles if noImplictAny is not turned on and isn't type-safe. WIth no implicit any you need an extra assertion Sort[key as keyof typeof Sort]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.