Dart中是否支持枚举类型的联合(Union)?
Dart中能否创建枚举的联合类型?
Dart原生不支持直接像TypeScript那样用|语法把多个枚举合并成一个新的联合枚举类型。因为Dart的枚举是独立的静态类型,每个枚举的实例都是各自枚举类的专属对象,没法直接合并成一个新枚举。
不过可以通过以下两种方式实现类似效果:
1. 用类+静态常量模拟联合枚举
手动创建一个类,把不同枚举的实例封装成类的静态常量,再提供统一的values列表,就能达到和联合枚举类似的使用体验:
enum Animal { cat, dog } enum Plant { tree, flower } class LivingCreature { final Object _value; const LivingCreature._(this._value); // 整合所有枚举值 static const cat = LivingCreature._(Animal.cat); static const dog = LivingCreature._(Animal.dog); static const tree = LivingCreature._(Plant.tree); static const flower = LivingCreature._(Plant.flower); // 模拟枚举的values列表 static const values = [cat, dog, tree, flower]; // 可选:添加类型判断方法,方便业务逻辑处理 bool get isAnimal => _value is Animal; bool get isPlant => _value is Plant; // 重写toString,调试时更直观 @override String toString() => _value.toString(); }
2. 借助代码生成工具实现类型安全的联合类型
如果项目里用了freezed这类代码生成库,可以利用它的联合类型特性,实现更严谨的类型检查:
import 'package:freezed_annotation/freezed_annotation.dart'; part 'living_creature.freezed.dart'; enum Animal { cat, dog } enum Plant { tree, flower } @freezed class LivingCreature with _$LivingCreature { const factory LivingCreature.animal(Animal value) = _Animal; const factory LivingCreature.plant(Plant value) = _Plant; } // 使用示例 void main() { final creature = LivingCreature.animal(Animal.cat); // 强制处理所有分支,避免遗漏 creature.when( animal: (animal) => print('这是动物:$animal'), plant: (plant) => print('这是植物:$plant'), ); }
关于你提到的“编译时集合联合”:Dart的枚举在编译阶段就固定了每个枚举的values列表和索引值,不同枚举的实例属于完全不同的类型,所以原生无法直接将多个枚举合并成一个新的枚举类型。枚举本质是特殊的类,每个枚举值都是该类的单例,没法跨枚举类整合。
内容的提问来源于stack exchange,提问作者jakobleck
相关产品推荐
相关产品推荐

