2

Given a union like this:

type MyUnion = 'foo' | 'bar' | 'baz';

How can I make a type like StrictArrayOfUnion. So that I can get the following results:

type MyStrictUnionType = StrictArrayOfUnion<MyUnion>;

// Arrays that do what I want
const a: MyStrictUnionType = ['foo', 'bar', 'baz'];
const b: MyStrictUnionType = ['foo', 'baz', 'bar']; // Passes since I assume there is no way to check ordering on a union

// However, all of these should not be allowed
const c: MyStrictUnionType = ['foo', 'bar']; // Fails due to missing 'baz'
const d: MyStrictUnionType = ['foo', 'foo', 'baz']; // Fails due to missing 'bar'
const e: MyStrictUnionType = ['foo', 'boo', 'baz']; // Fails due to missing 'bar'

Not caring about ordering here, just want to check if any union items are missing from the array.

Essentially I want a TS version of logic like this:

const myUnion = ["foo", "bar", "baz"]; // this would be a Union in a TS scenario
const hasAllUnionMembers = (arr) => myUnion.every(unionMember => arr.includes(unionMember));

JD Francis
  • 454
  • 1
  • 4
  • 22
  • If you want to disallow duplicates, then it's easily possible by generating all permutations. However, this breaks for larger unions since the number of permutations skyrockets past the union size limit. Either way, you can still do it with a helper function to do the inferencing and validation. – kelsny Mar 03 '23 at 23:30
  • 3
    [Here](https://tsplay.dev/m3xgLW) is a demo of the two methods. Note that the helper function I have shown does not protect against duplicates, *but* it is possible to make it error on duplicates. – kelsny Mar 03 '23 at 23:44

0 Answers0