Typescript: Is it possible to type an array to include every key of an enum

Viewed 2009

Is it possible to type the enum array in a way that forces it to contain every single value of the EPostFromField enum?

This is a mongodb schema, and the use case would be to future proof the enum field if more enums are added later on (ie: have the compiler throw an error because the array doesn't have all the enum values enumerated).

As a bonus I guess the next level would be a solution that also guarantees that the enum array values are unique :)

export const enum EPostFromField {
  Resident = 'resident',
  AdminUser = 'admin-user', // Admin <user name>
  BoardUser = 'board-user', // Board <user name>
  AdminSociety = 'admin-society', // Admin <community name>
  BoardSociety = 'board-society', // Board <community name>
}

showPostAs: {
    type: String,
    default: EPostFromField.Resident,
    enum: [
      EPostFromField.Resident,
      EPostFromField.AdminUser,
      EPostFromField.BoardUser,
      EPostFromField.AdminSociety,
      EPostFromField.BoardSociety,
    ] as EPostFromField[], // DEVNOTE: Improve typing to enforce *every* unique key of enum
  },
1 Answers

You could define a string enum and do the following:

enum EPostFromField {
    Resident = "Resident",
    AdminUser = "AdminUser",
    BoardUser = "BoardUser",
    AdminSociety = "AdminSociety",
    BoardSociety = "BoardSociety"
}

const epostFromFieldKeys = Object.keys(EPostFromField);

const epostFromFields = epostFromFieldKeys as EPostFromField[]

You can see this running in this playground link.

The values in the array would be unique if you define the string values in the enum uniquely(!).

Related