如何为 Type / T 实现 `assert()`

How to implement `assert()` for Type / T

重现:

请注意 dartpad ignores assert

class Foo<T> {
  Foo(this.data) : assert(T is int || T is String);
  final T data;
}

void main() {
  print('hello');
  final _fooInt = Foo<int>(1);
}

日志:

flutter: hello
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:type_test/main.dart': Failed assertion: line 2 pos 27: 'T is int || T is String': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      new Foo
package:type_test/main.dart:2
#3      main
package:type_test/main.dart:8
#4      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:136:25)
#5      _rootRun (dart:async/zone.dart:1186:13)
#6      _CustomZone.run (dart:async/zone.dart:1090:19)

如何正确实现第 2 行的断言? 谢谢

Dart JS 后端将 ints 视为 double。这就是您的代码不会抛出异常的原因。你可以阅读它 here.

已添加。你可以尝试这样的事情:

class Foo<T> {
  Foo(this.data) : assert(T == int || T == String);
  final T data;
}

void main() async {
  print('hello');
  // ok
  final _fooInt = Foo<int>(1);
  // ok
  final _fooStr = Foo<String>("Str");
  // fails
  final _fooDouble = Foo<double>(5.5);
}

来自 answer on r/flutterDev discord

Stampi

下面的更改解决了这个问题

class Foo<T extends int> {
- Foo(this.data) : assert(T is int || T is String);
+ Foo(this.data) : assert(T == int || T == String);
  final T data;
}

void main() {
  print('hello');
  final _fooInt = Foo<int>(1);
  print(_fooInt.data.runtimeType);
}