schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
148 stars 22 forks source link

Casting generic subtypes from dynamic (how to) #54

Open point-source opened 1 year ago

point-source commented 1 year ago

If I have a class such as MyClass<MySubtype> and an instance that has been deserialized into MyClass<dynamic>, how can I manually cast/convert it back into MyClass<MySubtype>?

I don't necessarily need to always do this as part of the deserialization, just occasionally on demand under specific circumstances.

I tried using copyWith like so: myInstance.copyWith<MyClass<MySubtype>>(); but copyWith doesn't appear to accept a type parameter in version 2.0.0-dev.11. I think I saw this functionality in an earlier version but am not 100% sure.

I also tried to use a container: myMapperContainer.fromValue<MyClass<MySubtype>>(myInstance); but mappable wants the instance to be a primitive such as a map. This makes sense but I don't want to serialize / deserialize just to change the subtype.

I'm probably missing something obvious here but even so, it might be helpful to document this somewhere.

schultek commented 1 year ago

I don't think this was ever supported, but its an interesting concept to make copyWith generic.