How to check the type is enum or not in typescript

前端 未结 4 1212
梦谈多话
梦谈多话 2021-01-23 13:23

I have a string enum type like:

export enum UserRole {
admin = "admin",
active = "active",
blocked = "blocked"
}

I

4条回答
  •  长情又很酷
    2021-01-23 13:42

    The value of an enum is either a string or number. So, they only way to test, is to test against a string or number.

    We can start by creating a User-Defined Type Guard which would look like this:

    function isInstance(value: string, type: T): type is T {
        return Object.values(type).includes(value)
    }
    

    This returns true or false if the value is found in the enum (This doesn't work well on numbers or enums with the same string).

    enum Animal {
        Cat = 'cat',
        Dog = 'dog'
    }
    
    enum Plant {
        Tree = 'tree',
        Flower = 'flower'
    }
    
    function isInstance(value: string | number, type: T): type is T {
        return Object.values(type).includes(value)
    }
    
    console.log(isInstance('dog', Animal)) // True
    console.log(isInstance('dog', Plant))  // False
    

提交回复
热议问题