Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[linter request] Don't use a non-nullable casting type when combined with conditional member access #59805

Open
Reprevise opened this issue Dec 25, 2024 · 0 comments
Labels
analyzer-linter Issues with the analyzer's support for the linter package area-analyzer Use area-analyzer for Dart analyzer issues, including the analysis server and code completion. type-enhancement A request for a change that isn't a bug

Comments

@Reprevise
Copy link

Dart should have a lint to ensure that users who combine conditional access and casting that the casting type is nullable. An alternative solution would be to have the user switch to using the bang (!) operator instead to show intent.

BAD:

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull?.single as bool; // Non-null type combined with conditional access, will throw a TypeError
}

void main() {
  final objects = <List<Object>?>[null, ["bar"], [2]];
  getBool(objects);
}

GOOD:

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull?.single as bool?; // Nullable type combined with conditional access, no TypeError
}

bool? getBool(List<List<Object>?> input) {
  return input.firstOrNull!.single as bool; // Using a bang operator instead
}

void main() {
  final objects = <List<Object>?>[null, ["bar"], [2]];
  getBool(objects);
}
@Reprevise Reprevise added the area-analyzer Use area-analyzer for Dart analyzer issues, including the analysis server and code completion. label Dec 25, 2024
@srawlins srawlins added analyzer-linter Issues with the analyzer's support for the linter package type-enhancement A request for a change that isn't a bug labels Dec 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
analyzer-linter Issues with the analyzer's support for the linter package area-analyzer Use area-analyzer for Dart analyzer issues, including the analysis server and code completion. type-enhancement A request for a change that isn't a bug
Projects
None yet
Development

No branches or pull requests

2 participants