-1

If I've got a string value, for example, from the server. And I defined an enum type with string values. How could I convert the string value to enum type in typescript?

export enum ToolType {
  ORA= 'orange', ST= 'stone' , DP= 'dupe'
}

const stringFromServer='orange';
// need TO transfer it  to ToolType.ORA
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
Tethys Zhang
  • 427
  • 5
  • 10
  • 1
    dose this https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript is your answer? – kushal shah Jan 19 '20 at 06:23
  • use type assertion `const stringFromServer = 'orange' as ToolType;` if you're sure that string is for sure one of the enum options – Aleksey L. Jan 19 '20 at 06:59
  • Does this answer your question? [How do I convert a string to enum in TypeScript?](https://stackoverflow.com/questions/17380845/how-do-i-convert-a-string-to-enum-in-typescript) – ford04 Jan 19 '20 at 09:24
  • Did any answer work for you? If yes, please do consider accepting/upvoting them! – Nicholas K Jan 20 '20 at 05:20

2 Answers2

1

If you want to get ORA if stringFromServer='orange' or ST if stringFromServer = 'stone'

Then you can try this:

Use Filter function of JavaScript and check for your condition. When it matches return true else return false. It will give you an array with your desired data

var value = 'orange';
let enums = Object.keys(ToolType).filter(x => 
{
  if(ToolType[x] === value){    
    return true;    
  }
  return false;
});

enums will be an array like

enums[0] = ORA

Working link:

https://stackblitz.com/edit/typescript-byg8ct

halfer
  • 19,824
  • 17
  • 99
  • 186
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

When the server sends an enum it actually send a number representing that enum and not its types.

You could do something like this:

type ToolType = 'Orange' | 'Stone' | 'Dupe';

const stringFromServer: ToolType = 'Orange';

You need somehoe in the client to know what are the numbers of your enum representation.

You could try modify your server to make him send you the string name of the enum and do the code I wrote above.

erano
  • 374
  • 1
  • 6