Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: how to search a const array?

Tags:

typescript

I just have a normal array.

  • I want the string literals out of an array for use in a type
  • I want to search the array with .includes()

These two things seem to be incompatible for some reason... How should I do this?

const x = ['a', 'b', 'c'] as const;
type somethingElse = typeof x[number]; // 'a' | 'b' | 'c'
x.includes('foo' as string);           // string not assignable to 'a' | 'b' | 'c'

ts playground


1 Answers

You can cast x to a string[] for the purposes of searching it.

const x = ['a', 'b', 'c'] as const;
type somethingElse = typeof x[number]; // 'a' | 'b' | 'c'
(x as readonly string[]).includes('foo'); // false
like image 124
isaactfa Avatar answered Oct 28 '25 02:10

isaactfa