Home > Enterprise >  How to reduce union types in typescript without using string?
How to reduce union types in typescript without using string?

Time:07-12

I have the following local state variable

 const [select, setSelect] = useState<'' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h'>('');

and I want to reduce this awkward looking union type, I still want to be specific but I don't want go with string my redux default state looks like following any idea how to improve both of these cases ? Please note my redux state extends further more.

export interface group {
  id: string;
  set: 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i'| 'j'| 'k';
  groupStatus: boolean;
}

CodePudding user response:

You can use a type alias here:

type AllowedValues = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i'| 'j'| 'k'

export type group = {
  id: string;
  set: AllowedValues;
  groupStatus: boolean;
}

 const [select, setSelect] = useState<'' | AllowedValues>('');
  • Related