dart-lang / language

Design of the Dart language
Other
2.61k stars 200 forks source link

if-null operator disables type checking #3843

Open abdallah-elsehaily opened 1 month ago

abdallah-elsehaily commented 1 month ago

When using if-null operator ?? in property initialization of a class properties it disables the type checking as I will be able to assign bool to int as follows

class CustomerDetails {
  int numOfDays;

  CustomerDetails.fromJson(Map<String, dynamic> json)
      : numOfDays = false ?? json['numOfDays'] ?? false;
}
lrhn commented 1 month ago

This is a known issue. The upper bound of bool and dynamic is dynamic, which is assignable to int.

The easiest fix to the language would be "Always coerce before LUB". which would coerce the dynamic from json['numOfDays'] to int before doing the least-upper-bound with bool.

Until then write it as false?? (json['numOfDays'] as int?) ?? false and get all the errors the code deserves. (Or at least some of them.)