2

I have an array of strings:

let foo = ["bar", "baz"];

I wish to perform something similar to keyof type foo, but for an array rather than an object:

type DESIRED_RESULT = "bar"|"baz";

Is there any way to convert all unique strings within an array to a type?

Rick
  • 8,366
  • 8
  • 47
  • 76

1 Answers1

1

foo is inferred as string[].
The array values don't enter the type system at all, so this is impossible.

If you put it in the type system, it becomes possible:

let foo: ["bar", "baz"];
let bar: typeof foo[number] = "";

Type '""' is not assignable to type '"bar" | "baz"'.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964