0

Before Typescript 2 version I used to convert enums to string in the following way:

public myFunction(myEnum: MyEnum): string {
   return MyEnum[myEnum];
}

Now with the new version of Typescript the following error is generated: An index expression argument must be of type 'string', 'number', 'symbol' or 'any'.

Do you have an idea how I could fix this?

1 Answer 1

1

I believe the error you are getting is that you declare that myFunction returns a string, but it actually doesn't return anything...

public myFunction(myEnum: MyEnum): string {
   console.log(MyEnum[myEnum]);
}

Fix it by returning the value...

public myFunction(myEnum: MyEnum): string {
   return MyEnum[myEnum];
}

Or by changing the return type...

public myFunction(myEnum: MyEnum): void{
   console.log(MyEnum[myEnum]);
}

Full example to show things do still work.

enum Example {
    Red,
    Blue,
    Green
}

alert(Example[Example.Red]);

function myFunction(myEnum: Example): string {
   return(Example[myEnum]);
}

alert(myFunction(Example.Blue));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. It is my fault I published incorrect code. In fact this is not the problem. It is related to this announcement: blogs.msdn.microsoft.com/typescript/2016/08/30/…, but I am not sure how to fix it. I have the same code, it compiles without errors with TypeScript 1.9 and has errors in later TypeScript

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.