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'
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'
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]) => {};