Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: how to search a const array?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading