Effect CommunityEC
Effect Community3y ago
12 replies
oh_lawd

Implementing String Enum Validation in TypeScript

I'm trying to implement a few types to make a function to only accept strings that are part of an array.

export type EnumShape<T> = [T, ...T[]]

class Container<Enum extends EnumShape<string>> {
  referencedEnum: Enum
  defaultValue: string

  constructor(referencedEnum: Enum) {
    this.referencedEnum = referencedEnum
  }

  public default(key: /** what type we need here */) {
    this.defaultValue = key
  }
}

let container = new Container(["A", "B"])

container.default("A") // this has to compile
container.default("C") // this is a type error

Is this even possible in TypeScript, or should I just do a runtime check?
Was this page helpful?