dart-lang / dart-lang/language

Type Promotion on Record Attributes

Open
#4,165 2 comments 2 reactions 0 assignees View on GitHub
feature field-promotion type-inference
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

When accessing a field in a record, the static analyzer is not able to do type promotion. If you destructure the fields into local variables, type promotion works.

See:
```dart
void main() {
// These do not work:
final (int?, Object) foo = (1, 'asdf');
if (foo.$1 == null) return;
// Null reference static analysis error.
print(foo.$1 + 1);
if (foo.$2 is! String) return;
// Method `length` not found on `Object`...
print(foo.$2.length);

// These do:
final (int? a, Object b) = (1, 'asdf');
if (a == null) return;
print(a + 1);
if (b is! String) return;
print(b.length);
}
```

For fields on classes, type promotion is not possible, or at the very least would require some complex caveats and changes in the language spec: https://github.com/dart-lang/language/issues/1415

But records can't have getters and aren't sub-classable, so as far as I can tell, there should be no barriers to type promotion in theory. This would be very helpful to our team as currently we return records from functions regularly and ALWAYS destructure at call site to ensure type promotion, which in turn means adding more fields to a record bloats the call site namespace.
Partial destructuring would also solve our problem: https://github.com/dart-lang/language/issues/3964

Contributor guide

Open the contributing guide

Research direction

Start with the Dart example in the issue and compare the record-field behavior with the destructured-local behavior. Read the linked language issues 1415 and 3964 to understand the stated caveats and related proposal; done means the language-specification direction and expected promotion behavior are clearly resolved.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.