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: type inference when using Array.find

why the env can’t be a enum type contains all items of list, and how?

const { hostname, pathname } = window.location
const rootDir = pathname.split('/')[1]
const list = ['newstage', 'stage', 'qa3', 'qa2', 't1', 'sit', 'dev']
const env = list.find(el => rootDir === el)

now env is const env: string, what I want is
const env: "stage" | "qa3" | "qa2" | "t1" | "sit" | "dev"

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 :

Try use const
assertions
:

no literal types in that expression should be widened (e.g. no going from "hello" to string)

const rootDir = 'qa3';
const list = ['newstage', 'stage', 'qa3', 'qa2', 't1', 'sit', 'dev'] as const;
const item = list.find(el => rootDir === el)

TypeScript Playground

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