You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将泛型类型A<Object>的对象强制转换为A<bool>类型

How to cast A<Object> to A<bool> in Dart when you know the actual value is a bool?

Problem Context

I'm working with this Dart code:

class A<T> { 
  A(this.a); 
  final T a; 
} 
void main() { 
  final a = A(true); 
  print(a); 
  print(a as A<bool>); 
  final b = A<Object>(true); 
  print(b); 
  print(b as A<bool>); 
}

I get an object b from a third-party library/API that's typed as A<Object> (I can't change its type definition). But in my specific business scenario, I know for sure this object's actual value should be A<bool>. When I try to cast it directly with as A<bool>, I hit a runtime error:

Instance of 'A<bool>'
Instance of 'A<bool>'
Instance of 'A<Object>'
Uncaught Error: TypeError: Instance of 'A<Object>': type 'A<Object>' is not a subtype of type 'A<bool>'

Solution

The core issue here is that Dart's generic types are reified (their type info stays intact at runtime) and generic classes are invariant by default. That means even though bool is a subtype of Object, A<bool> and A<Object> are treated as completely separate types—so a direct cast fails.

Since you're 100% certain the underlying value is a bool, you can work around this by using a dynamic intermediate cast to bypass strict type checking temporarily:

void main() {
  final b = A<Object>(true);
  // Use dynamic to bypass type checks for the cast
  final bCast = b as dynamic as A<bool>;
  print(bCast); // Outputs: Instance of 'A<bool>'
  print(bCast.a); // Outputs: true (type is bool)
}

Why this works

Casting to dynamic first tells the Dart compiler to pause type checking for that step. The second as A<bool> relies on your confirmed knowledge that the object's state matches the target type—since you know a is a bool, this cast will succeed at runtime.

Key Warning

This is an unsafe workaround if used without certainty. Only use it when you can guarantee the A<Object> instance's a property is exactly the type you're casting to. If the actual value doesn't match, you'll get a runtime error later when accessing a.

For cleaner reuse, you can wrap this logic in a helper function:

A<T> unsafeCastA<T>(A<Object> instance) {
  return instance as dynamic as A<T>;
}

// Usage example:
final bCast = unsafeCastA<bool>(b);

内容的提问来源于stack exchange,提问作者Valentin Vignal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:07:27