简体   繁体   中英

Typescript enum value as array parameter

I will first of all state, that I am using TypeScript2.4, so I can use string ENUMs, ala

export enum PermissionScope {
BRAND = "brand",
IMAGE_MARKER = "image-marker",
COMPANY = "company",
PRODUCT = "product",
FINANCIALS = "financials"
}

I don't know how to do 2 things.

  1. How can I type guard an enum, say

    class A { let a : PermissionScope; }

now when I try to instantiate this variable by

A.a = PermissionScope.BRAND

I get an error

Type 'string' is not assignable to type 'PermissionScope'.

This can kindof be fixed by

A.a = <PermissionScope> PermissionScope.BRAND

But I'm unsure if this is the right solution because as I understand, the underlying problem is that the variable is expected to be of a PermissionScope Enum Object type, not of a valid Enum value from PermissionScope.

How can I set the variable type so that it can only be one of the types from the enum?

The second question is.

  1. What if I want to ask if a string is a valid Enum value, aka

    var a = "brand"; //true var b = "candy crush" //false

For the first question, what you're trying to do shouldn't be a problem.
The 'let' inside your class may be causing your issues, I changed that to public and had no issues.
I also assume that your Aa example is meant to be an instance of A? your variable 'a' is an instance variable.

class A {
    public a : PermissionScope = PermissionScope.BRAND;
}
const instance = new A();

instance.a = PermissionScope.BRAND;

Answering your second question, the enum gets converted to an object under the hood. Which looks like this in raw js

var PermissionScope;
(function (PermissionScope) {
    PermissionScope["BRAND"] = "brand";
    PermissionScope["IMAGE_MARKER"] = "image-marker";
    PermissionScope["COMPANY"] = "company";
    PermissionScope["PRODUCT"] = "product";
    PermissionScope["FINANCIALS"] = "financials";
})(PermissionScope = exports.PermissionScope || (exports.PermissionScope = {}));

So you can see if the static part of your enum is valid using 'in'

console.log('BRAND' in PermissionScope); //true
console.log('IMAGE_MARKER' in PermissionScope); //true
console.log('ASDF' in PermissionScope); //false

If you want to check the value part of the enum you would have to iterate through the object values and check that

function isValidEnumValue(enumType: any, value: string) {
    //NOTE: Object.values is only available in ES7 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values)
    return Object.values(enumType).indexOf(value) !== -1;
}

console.log(isValidEnumValue(PermissionScope, 'brand')); //true
console.log(isValidEnumValue(PermissionScope, 'asdf')); //false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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