Dynamic types from arrays for a class method

Viewed 44

I would like to get the values from an array as types, something like this:

const chars = ['a','b','c'] as const

type TChars = typeof chars[number] // 'a'| 'b' | 'c'

I would like to do the same but for class methods and properties, like this:

class Test{
  constructor(public chars:string[]){}

  get(char:string){
    return char
  }
}

new Test(['a','b','c']).get('d') //error only allow a,b or c

So the get() method should only allow the initial characters passed to the constructor.

I am open to refactoring the class signature.

TS Playground

1 Answers

Almost exactly the same way, except you need to make the class the generic and then use that generic to tell get to only accept the values in the array.

TS Playground

class Test<T extends readonly string[]> {
  constructor(public chars: T) {}

  get(char: T[number]) {
    return char;
  }
}

//error only allow a,b or c
new Test(["a", "b", "c"] as const).get("d");
Related