简体   繁体   English

迭代枚举时如何排除命名空间函数?

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

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:当我遍历JournalEntryType并像这样记录每个值时:

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

The last value that is printed won't be ANIMAL_SIGHTING but getJournalEntryTypeColor .打印的最后一个值不是ANIMAL_SIGHTING而是getJournalEntryTypeColor In other words, it also iterates over any functions that are declared in the namespace .换句话说,它还遍历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 journalType is a string.我尝试使用 if 语句过滤掉该方法,该语句检查journalType的类型是否为字符串。 But that won't stop from getJournalEntryTypeColor getting printed as well.但这不会因为getJournalEntryTypeColor被打印而停止。

The key thing is that you need to check the type of the property on the object, not the type of the key.关键是你需要检查object上的属性类型,而不是键的类型。

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.) (此代码取自评论,由 Maurice 编写。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM