1 year ago

#71582

test-img

Mukil Deepthi

Typescript how to get enum key as enum by value and retrieve value from Map?

I have a simple code in angular code to retrieve file image icon based on extension:

export enum FileExtension {
    PDF = 'pdf',
    JPEG = 'jpeg'
}

export const FileExtensionIconMap = new Map<FileExtension, string>([
    [FileExtension.PDF, 'fas fa-file-pdf'],
    [FileExtension.JPG, 'fas fa-file-image']
}   

method to retrieve iconName based on file extension:

let iconName = '';
switch (fileExtension) {
    case FileExtension.PDF:
        iconName = FileExtensionIconMap.get(FileExtension.PDF);
        break;
    case FileExtension.PNG:
        iconName = FileExtensionIconMap.get(FileExtension.PNG);
        break;
    
}
return iconName;    

I have long list of files. Instead of using switch case is there a wayto get value from the Map?

ie. from the 'fileExtension' which will have for eg: 'pdf' is there a way to retrieve the enum key ie. FileExtension.PDF so that i can make this logic in one single line to get value from the map?

tried the following and getting undefined as the result

let x = <FileExtension>FileExtension['pdf'];

typescript

angular11

0 Answers

Your Answer

Accepted video resources