dartanalyzerdart-analyzer

How to get the subtypes of a generic type using `DartType` from `analyzer` package?


How can I get the subtypes of an element using the class DartType from the analyzer package?

for example if the type is List<String>, I would like to get String. Also will be useful to get if the type is generic.

Another more complex example would be Map<String, String> where I want to get a list of the subtypes, in this case: [String, String].


Solution

  • This one is a little tricky - because DartType actually itself has some super types - the one that will interest you here is ParameterizedType:

    import 'package:analyzer/dart/element/type.dart';
    
    Iterable<DartType> getGenericTypes(DartType type) {
      return type is ParameterizedType ? type.typeArguments : const [];
    }
    

    I don't know if it's possible to know if the type is generic - after all, it's just a type. But you can check if the type accepts generic parameters, again, using ClassElement:

    import 'package:analyzer/dart/element/element.dart';
    import 'package:analyzer/dart/element/type.dart';
    
    bool canHaveGenerics(DartType type) {
      final element = type.element;
      if (element is ClassElement) {
        return element.typeParameters.isNotEmpty;
      }
      return false;
    }
    

    Hope that helps!