0

I have a case:

const types = ['a', 'b', 'c'];
const fn = (arg: *in types*) => {};

Is there a way to tell Typescript that arg can have type of any element in types array?

Note: I dont want to hardcode it, e.g. arg: 'a' | 'b' | 'c'

Patrickkx
  • 1,740
  • 7
  • 31
  • 60

1 Answers1

2

Yes! You have to adjust the type inference of the array with as const (that changes the type from string[] to ("a" | "b" | "c")[]), then you can lookup (typeof types)[number].

 const types = ['a', 'b', 'c'] as const;
 const fn = (arg: (typeof types)[number]) => {};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151