简体   繁体   中英

Typescript: How to use an enum to enforce that an array will contain specific values only from that enum?

I have an HTTP service in Angular that returns the accesses allowed for a particular user. The sample response is as follows:-

{
    "accessId": 4209318492034,
    "folderPath": "data/sample_folder/",
    "permissions": [
        "READ",
        "WRITE"
    ]
}

Specifically the permissions field is an array that will contain only the following strings, "READ" (compulsory) and "WRITE" (optional, may or may not be present).

I want to type this response using an interface, and for sake of enforcing the presence of only these strings in the permissions array, I created an Enum as follows:-

enum Permissions {
    READ = 'READ',
    WRITE = 'WRITE'
}

But using it in the interface for the response as follows does not work:-

export interface UserAccess {
    accessId: string;
    folderPath: string;
    permissions: Permissions[]
}

How do I enforce that the permissions array will contain values ONLY from the defined Permissions string enum?

don't use enum, use type:

export type Permissions = 'READ'|'WRITE'

export interface UserAccess {
    accessId: string;
    folderPath: string;
    permissions: Permissions[]
}

You might want to try the following:

export interface UserAccess {
  permissions:  (keyof typeof Permissions)[]
}

Note: TypeScript is just a compile-time concept and does not enforce anything at runtime.

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