reactjs - 如何在 TypeScript 中减少联合类型而不使用字符串?
我有以下本地状态变量
const [select, setSelect] = useState<'' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h'>('');我想减少这个看起来很尴尬的联合类型,我仍然想保持具体,但我不想使用字符串。我的 Redux 默认状态如下,有什么方法可以改善这两种情况吗?请注意,我的 Redux 状态还有更进一步的扩展。
export interface group {
id: string;
set: 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i'| 'j'| 'k';
groupStatus: boolean;
}答案#1
你可以在这里使用类型别名:
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>('');
