Skip to main content

move-records-to-typedefs

added in: 1.5.0
⚙️🛠
Dart 3.0+
Pro+

Warns when a record type should be moved to a typedef.

Although records allow to group data without introducing a class, when a record type is changed in one place, all other record type declarations that accept the same record require an update as well.

A good way to solve this problem is to move a repeating record type declaration to a typedef.

info

This rule also highlights issues if a file uses or declares a record typedef and has a record with the same structure as typedef used directly.

⚙️ Config

Set min-fields (default is 5) to configure the minimal number of record fields after which the rule should trigger.

Set min-occurrences (default is 3) to configure the minimal number of occurrences after which the rule should trigger.

analysis_options.yaml
dart_code_metrics:
rules:
- move-records-to-typedefs:
min-fields: 5
min-occurrences: 3

Example

❌ Bad:

import 'external_typedef.dart';

typedef MyDataClass = (String, int);

class MyClass {
MyDataClass getPoint() => ('1', 1);

// LINT: This record type can be replaced with the existing 'MyDataClass' typedef. Try using it instead.
(String, int) getOtherPoint() => ('1', 1);
}

// LINT: Prefer declaring a typedef for this record type.
(
double,
double,
double,
double,
double,
) _longRecordType() {}

// LINT: This record type can be replaced with the existing 'External' typedef. Try using it instead.
(String, int, int) _withoutExternalTypedef() {}

External _withExternalTypedef() {}

✅ Good:

import 'external_typedef.dart';

typedef MyDataClass = (String, int);

class MyClass {
MyDataClass getPoint() => ('1', 1);

MyDataClass getOtherPoint() => ('1', 1); // Correct, uses the typedef instead
}

typedef SomeType = (double, double, double, double, double);

SomeType _longRecordType() {}

External _withExternalTypedef() {}

External _alsoWithExternalTypedef() {}