Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
arg
types
Note: I dont want to hardcode it, e.g. arg: 'a' | 'b' | 'c'
arg: 'a' | 'b' | 'c'
any
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].
as const
string[]
("a" | "b" | "c")[]
(typeof types)[number]
const types = ['a', 'b', 'c'] as const; const fn = (arg: (typeof types)[number]) => {};
Add a comment
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
anyas the type?anywhen there is a concrete type the variable could be?