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'

2
  • Why not use any as the type? Commented Mar 5, 2020 at 18:07
  • 1
    @AnuragSrivastava why use any when there is a concrete type the variable could be? Commented Mar 5, 2020 at 18:08

1 Answer 1

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]) => {};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.