Skip to content

Instantly share code, notes, and snippets.

@rydmike
Created November 9, 2025 15:16
Show Gist options
  • Select an option

  • Save rydmike/2ace800b1423efcad5f2f6ea5742d9f8 to your computer and use it in GitHub Desktop.

Select an option

Save rydmike/2ace800b1423efcad5f2f6ea5742d9f8 to your computer and use it in GitHub Desktop.
Two ways of comparing if two generics are of same type in Dart. There is a slight diff between these ways that may be important in some cases.
/// Check whether two types are the same type in Dart when working with
/// generic types.
///
/// Uses the same definition as the language specification for when two
/// types are the same. Currently the same as mutual sub-typing.
bool sameTypes<S, V>() {
void func<X extends S>() {}
// Dart spec says this is only true if S and V are "the same type".
return func is void Function<X extends V>();
}
bool equalTypes<S, V>() {
return S == V;
}
class Nothing {}
class Something extends Nothing {}
void main() {
//
print(sameTypes<int, int>()); // true
print(sameTypes<int, int?>()); // false
print(equalTypes<int, int>()); // true
print(equalTypes<int, int?>()); // false
print('');
//
print(sameTypes<Nothing, Nothing>()); // true
print(sameTypes<Nothing, Nothing?>()); // false
print(equalTypes<Nothing, Nothing>()); // true
print(equalTypes<Nothing, Nothing?>()); // false
print('');
//
print(sameTypes<List<dynamic>, List<Object>>()); // false
print(sameTypes<List<dynamic>, List<Object?>>()); // true
print(equalTypes<List<dynamic>, List<Object>>()); // false
print(equalTypes<List<dynamic>, List<Object?>>()); // false
print('');
//
print(sameTypes<Nothing, Something>()); // false
print(sameTypes<Nothing?, Something?>()); // false
print(equalTypes<Nothing, Something>()); // false
print(equalTypes<Nothing?, Something?>()); // false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment