0

I'm trying to create an exhaustive typecheck for an array from a type alias.

type Elevation = '1' | '2' | '3';

type SomeExhaustiveType = ???

const elevationArray: SomeExhaustiveType<Elevation>[] = ['1', '2']; // <-- show error here because 3 is not in the array

Is it possible to check if all members of type Elevation are in elevationArray?

That Guy
  • 154
  • 2
  • 14
  • care to share the typescript version? – Pranav Aug 28 '20 at 08:23
  • I'm not getting an error https://stackblitz.com/edit/react-ts-pjsch1?file=Hello.tsx – Mike K Aug 28 '20 at 08:23
  • It is correct; no errors : https://www.typescriptlang.org/play?ts=3.9.2#code/C4TwDgpgBAogNhAbgQ2ASwPYDsoF4oDkAjAVAD6EBMpFBAzAQNwBQzAxtgM7BQQIrpsAQQBOI5CABcsfqkxYA2gF08UBcQIAaKgSWMgA – Pranav Aug 28 '20 at 08:24
  • it won't show errors because elevationArray does not contain invalid members of Elevation type. However, I want to check that all members of `type Elevation` are in `elevationArray`. I'm sorry I wrote the question in a misleading way. – That Guy Aug 28 '20 at 08:26
  • 3
    Why not generate the union *from* an exhaustive array/tuple of values? See e.g. https://stackoverflow.com/questions/44480644/typescript-string-union-to-string-array – jonrsharpe Aug 28 '20 at 08:29
  • @jonrsharpe Thank you, that's what I was looking for! If you want I'll mark it as the answer, just post it below. – That Guy Aug 28 '20 at 08:35

0 Answers0