Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic types from arrays for a class method

Tags:

typescript

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

like image 763
Ivan V. Avatar asked Jul 05 '26 05:07

Ivan V.


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");
like image 141
Nishant Avatar answered Jul 07 '26 08:07

Nishant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!