google / google/json_serializable.dart
Invalid generated code when `typedef` refers to unimported file
- Dominant language
- Dart
- Stars
- 1.6k
- Forks
- 461
- Avg merge
- 45m
- Merged PRs (30d)
- 1
Description
When a field refers to a `typedef`'d type, the generated code uses the original type name rather than its alias. However, if the original type isn't currently imported, the generated code doesn't compile.
A minimal testcase project is provided at [mernen/testcase_serialize_typedef.dart](https://github.com/mernen/testcase_serialize_typedef.dart).
Basically, imagine a project with the following structure:
- `impl_details.dart` contains a class called `UserImpl`, with a `UserImpl.fromJson()` constructor (may or may not use `@JsonSerializable()`)
- `user.dart` imports `impl_details.dart` (without exporting anything) and defines `typedef User = UserImpl;`
- `comment.dart` imports `user.dart`, declares a class `Comment` that refers to `User`, and uses `@JsonSerializable()` to generate a `fromJson()` factory
After `build_runner` runs, `comment.g.dart` will attempt to use `UserImpl.fromJson(...)` to instantiate the `User`, but that name isn't imported!
Since part declarations can't themselves `import` anything, perhaps the only possible solution here (without the aid of the developer) would be to use the aliased name in this case.
## Tested versions
* `json_serializable`: 6.1.5
* Dart SDK version: 2.16.2 (stable)
* Flutter 2.10.4 • channel stable
Contributor guide
Assessment
This issue has not been assessed yet.