Home > Enterprise >  TypeScript: type inference when using Array.find
TypeScript: type inference when using Array.find

Time:01-10

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"

CodePudding user response:

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

  •  Tags:  
  • Related