Skip to main content

avoid-casting-to-extension-type

added in: 1.15.0
🛠
Dart 3.3+
Pro+
preset: recommended

Warns when an expression is casted to an extension type.

Casting to an extension type can throw at runtime, whereas instantiating it is safe and you'll get a hint about the representation field type mismatch.

Example

❌ Bad:

void fn(String input) {
// LINT: Avoid casting to extension type. Try instantiating it instead.
final value1 = input as ET;

// LINT: Avoid casting to extension type. Try instantiating it instead.
final value2 = input as ET1;
}

extension type const ET(String s) {}
extension type const ET1(int v) {}

✅ Good:

void fn(String input) {
final value = ET(input); // Correct, instantiated instead
}

extension type const ET(String s) {}

Additional Resources