How do i exclude namespace functions when iterating over an enum?

Viewed 110

I have the following code

export enum JournalEntryType {
    ORDINARY_JOURNAL_ENTRY = 'ORDINARY_JOURNAL_ENTRY',
    PLANT_TRANSPLANTED = 'PLANT_TRANSPLANTED',
    SOW_SEEDS = 'SOW_SEEDS',
    SEEDS_GERMINATED = 'SEEDS_GERMINATED',
    PLANT_BLOSSOMS = 'PLANT_BLOSSOMS',
    FRUIT_SETTING = 'FRUIT_SETTING',
    FRUIT_CHANGED_COLOR = 'FRUIT_CHANGED_COLOR',
    HARVEST = 'HARVEST',
    ANIMAL_SIGHTING = 'ANIMAL_SIGHTING'
}

export namespace JournalEntryType{
    export function getJournalEntryTypeColor(journalEntryType: string): string{
        switch(journalEntryType){
            case JournalEntryType.ORDINARY_JOURNAL_ENTRY.toString(): return '#FFFFFF';
            case JournalEntryType.PLANT_TRANSPLANTED.toString(): return '#8B4513';
            case JournalEntryType.SOW_SEEDS.toString(): return '#D2691E';
            case JournalEntryType.SEEDS_GERMINATED.toString(): return '#7CFC00';
            case JournalEntryType.PLANT_BLOSSOMS.toString(): return '#FFB6C1';
            case JournalEntryType.FRUIT_SETTING.toString(): return '#FF69B4';
            case JournalEntryType.FRUIT_CHANGED_COLOR.toString(): return '#ff1493';
            case JournalEntryType.HARVEST.toString(): return '#DC143C';
            case JournalEntryType.ANIMAL_SIGHTING.toString(): return '#800080';
            default: throw new Error();
        }
    }
}

When i iterate over JournalEntryType and log every value like so:

for(let journalType in JournalEntryType){
    console.log(journalType);
}

The last value that is printed won't be ANIMAL_SIGHTING but getJournalEntryTypeColor. In other words, it also iterates over any functions that are declared in the namespace. How do i prevent this from happening? I've tried filtering out the method with an if statement that checks whether the type of the journalTypeis a string. But that won't stop from getJournalEntryTypeColor getting printed as well.

1 Answers

The key thing is that you need to check the type of the property on the object, not the type of the key.

Object.keys(JournalEntryType)
    .filter(journalType => !(typeof(JournalEntryType[journalType]) === 'function'))
    .forEach(journalType => { 
        //code here
    });

(This code is taken from the comments, it was written by Maurice.)

Related