1

I have an enum on angular like

export enum Status{
    Pending = 1,
    Working = 2,
    Finish = 3
}

using

var name = GetName<Status>(Status);

and I have other method to get name of enum

export function GetName<T>(en: T): string{
    // I want to get name here to result 'Status'
}

2 Answers2

1

To my knowledge you can't do this with Enumerators, however, if you created a typed map object, you could assert it's type by looking for a unique property like so:

enum Status {
    Pending = 1,
    Working = 2,
    Finish = 3
}

interface StatusMap {
 pending: Status.Pending;
 working: Status.Working;
 finish: Status.Finish;
}

const obj: StatusMap = { pending: Status.Pending, working: Status.Working, finish: Status.Finish };

function checkIfStatus(obj: StatusMap): 'Status' | 'NotStatusOrSomething' { 
 if ('pending' in obj) { 
   return 'Status'
  } else {
    return 'NotStatusOrSomething'
  }
}
Yeysides
  • 1,262
  • 1
  • 17
  • 27
0

Technically, enum is an Object in typescript.

So function could be

export function getName<T>(enumObject: T, value: any): string {
  Object.keys(enumObject).find(key => {
    return enumObject[key] === value;
  });
}
Liu Zhang
  • 1,808
  • 19
  • 31