Answer the question
In order to leave comments, you need to log in
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>;
type Validator<U extends string, A extends ReadonlyArray<string>> =
A[number] extends U
? U extends A[number]
? U
: never
: never;
Answer the question
In order to leave comments, you need to log in
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;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question