Important
NB! I’m looking for volunteers with a strong understanding of Dart AST structures and analyzer packages, who have some free time and are willing to actively contribute to bringing
UnionTypeto Dart.
NB! At the moment, the core component (
UnionTypeVisitor) was fully generated by AI. It works for certain cases, but I’m not entirely sure why or how. To be more confident, I’ve added tests that cover the known cases.
union_type_lint
union_type_lint is a Dart analyzer plugin that validates @UnionType annotations at analysis time.
It enforces type safety by reporting warnings when values assigned to union types do not match any of the allowed types declared in the annotation.
Features
- Validates assignments to
@UnionTypetypedefs at compile time - Works with function typedefs and interface/class types
- Integrates seamlessly with the Dart analyzer
Getting started
Add union_type_lint as a dev dependency in your pubspec.yaml:
dev_dependencies:
union_type_lint: ^1.0.0
You will also need the annotation package:
dependencies:
union_type_annotation: ^1.0.0
Enable the plugin in analysis_options.yaml:
plugins:
union_type_lint: ^1.0.0
Usage
The plugin automatically validates your union types when you use the @UnionType annotation:
import 'package:union_type_annotation/union_type_annotation.dart';
typedef VoidCallback = void Function();
typedef OnTapCtx = void Function(BuildContext);
abstract class IOnTap { void onTap(BuildContext context, dynamic data); }
@UnionType([VoidCallback, OnTapCtx, IOnTap])
typedef OnTap = dynamic;
class TestClass {
final OnTap? onTap;
const TestClass(this.onTap);
}
void notify(OnTap fn) {
print('notify: $fn');
}
void main() {
// ✅ Valid assignments (no warnings)
final valid1 = TestClass(() => print('callback'));
final valid2 = TestClass((BuildContext ctx) => print('with context'));
final valid3 = TestClass(const MyOnTap()); // implements IOnTap
// ❌ Invalid assignments (analyzer warnings)
final invalid1 = TestClass((int value) => print('invalid'));
final invalid2 = TestClass(const MyInvalidOnTap()); // doesn't implement IOnTap
// ✅ Valid function parameter
notify(() => print('valid'));
// ❌ Invalid function parameter (analyzer warning)
notify((double v) => print('invalid'));
}
The analyzer will report warnings like:
'{0} does not match any allowed type in @UnionType {1}: [{2}].'
Note: Validation is performed only at analysis time. The plugin does not add any runtime overhead to your code.
How it works
The plugin registers a custom analysis rule that:
- Scans your code for
@UnionTypeannotations - Tracks typedefs marked with
@UnionType - Validates assignments and function parameters against the allowed types
- Reports warnings when types don't match
Additional information
- Issues and contributions: please use the GitHub repository.
- License: MIT