Home > Software design >  Typescript: how to search a const array?
Typescript: how to search a const array?

Time:08-11

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

CodePudding user response:

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
  • Related