google / google/reflectable.dart
Provide access to a type from a `TypeMirror`
- Dominant language
- Dart
- Stars
- 386
- Forks
- 67
- PR merge metrics
- No merged PRs in 30d
Description
A `TypeMirror` has a member `hasReflectedType` and a member `reflectedType`, and the latter returns a `Type` for the type which is mirrored by this `TypeMirror`.
Here is an example of the kind of data provided by `reflectedType`:
```dart
[
prefix0.A,
const r.FakeType(r'test_reflectable.test.class_property_test._B'),
prefix0.D,
prefix0.C
]
```
In many cases, these `Type` objects are obtained by evaluating a typename denoting a class or type alias (for instance, the library imported with prefix `prefix0` above contains `class A`, `class C`, `class D`).
We could actually create a construct that would enable the use of such types as types:
```dart
())>[
(f) => f(),
(f) => throw "Cannot `callWithReflectedType` when type is private",
(f) => f(),
(f) => f(),
];
```
The `TypeMirror` class would have a new member `callWithReflectedType`:
```dart
abstract class TypeMirror implements DeclarationMirror {
...
void callWithReflectedType(void Function() f) =>
reflector.typeCallers[reflectedTypeIndex](f);
...
}
```
We would then be able to use it as follows:
```dart
@reflector
class C {}
void main() {
TypeMirror typeMirror = reflector.reflectType(C);
late Map map;
if (typeMirror.hasReflectedType) { // This will be true, so we ignore the `else` case.
typeMirror.callWithReflectedType(() => map = {});
}
}
```
The callback which is passed to `callWithReflectedType` will receive the actual type mirrored by the `TypeMirror` as a normal Dart type argument, which means that we can use that type under the name `X` (or whatever we choose to call the type variable of the callback). For instance, we can create a `Map` when the type mirror is a mirror of `C`.
Contributor guide
Assessment
This issue has not been assessed yet.