A
A
artr_lr2020-10-21 01:33:24
typescript
artr_lr, 2020-10-21 01:33:24

Checking array values?

Let's say I have a union type
type U = 'foo' | 'bar';

How do I make sure the array contains all these values?
I tried something like this:

type Validator<U extends string, A extends ReadonlyArray<string>> =
  A[number] extends U
    ? U extends A[number]
      ? A
      : never
    : never;
  
type U = 'foo' | 'bar';
const arr = ['foo'] as const;

type R = Validator<U, typeof arr>;

Everything typechecks fine... The typescript outputs ['foo']. Although I expected to see an error!

And if I rewrite it like this:
type Validator<U extends string, A extends ReadonlyArray<string>> =
  A[number] extends U
    ? U extends A[number]
      ? U
      : never
    : never;

Then the type inference will show that it takes a specific value 'foo' from the union type - the very only value that is in the array... I don't understand anything...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-10-21
@artr_lr

type Validator<U extends string, A extends ReadonlyArray<string>> =
  (U extends A[number] ? true : false) extends true ? A : never;
  
type U = 'foo' | 'bar';
const arr0 = ['foo'] as const;
const arr1 = ['bar'] as const;
const arr2 = ['foo', 'bar'] as const;

type A0 = Validator<U, typeof arr0>; // never
type A1 = Validator<U, typeof arr1>; // never
type A2 = Validator<U, typeof arr2>; // readonly ['foo', 'bar']

const _check0: A0 = arr0; // error
const _check1: A1 = arr1; // error
const _check2: A2 = arr2;

https://www.typescriptlang.org/play?#code/C4TwDgpg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question