0

If one has a string array say,

const myArray = ["apple", "banana"]

How would one type this in TypeScript so that is satisfies any/all of the following:

["banana", "apple"]
["banana"]
["apple"]

I thought I could do something like:

const myArray = ["apple", "banana"] as const
type MyArrayType = typeof myArray;

But that doesn't seem to work as expected.

skube
  • 5,867
  • 9
  • 53
  • 77
  • 2
    `("apple" | "banana")[]`? Should `[]` be valid? Should `["apple", "banana", "carrot"]`? `["apple", "banana", "apple"]`? – jonrsharpe Dec 01 '22 at 14:07
  • Correct. `[]` and anything other than a subset of the original array should be invalid. – skube Dec 01 '22 at 14:11
  • How big will your set of strings be? If it's more than about five or six then the union-of-all-possible-valid-tuples is, while easy to generate, too unwieldy to be useful. – jcalz Dec 01 '22 at 14:17
  • I apologize if I'm using the wrong terminology. The length of array (of strings) wouldn't be more than say, six. Duplicates should be disallowed. – skube Dec 01 '22 at 14:22
  • 1
    So does [this approach](https://tsplay.dev/mAdyvN) meet your needs? Note that for six elements, you get a union of ~2K members. The compiler can handle that. For seven elements that jumps to ~14K... again, the compiler can handle that, but you might notice slowdowns. For eight, it's more than 100K and TypeScript will probably explode. If this approach works for you I can write up an answer explaining; otherwise, what am I missing? (Please mention @jcalz to notify me if you reply) – jcalz Dec 01 '22 at 14:35

1 Answers1

1

Almost. Use it like this

const myArray = ["apple", "banana"] as const
type MyArrayType = Array<typeof myArray[number]>

const test: MyArrayType = ["apple"]
const test1: MyArrayType = ["banana"]
const test2: MyArrayType = ["banana", "apple"]
const test3: MyArrayType = ["banana", "apple", "kiwi"] // error

For uniqueness check you can use the type with one of the examples here Is there a way to define type for array with unique items in typescript?

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107