RNNewArchitectureApp icon indicating copy to clipboard operation
RNNewArchitectureApp copied to clipboard

How to declare objects with methods in TypeScript spec file?

Open asfernandes opened this issue 3 years ago • 3 comments

For example, in https://github.com/react-native-community/RNNewArchitectureApp/blob/run/pure-cxx-module/tm/NativeSampleModule.ts if CustomType has methods, how to declare them?

asfernandes avatar Jan 14 '23 02:01 asfernandes

Hi @asfernandes. I don't think that you should do that. Those object are meant to be data object, which only contains data. If you need to provide behaviors, then you should implement that in your Native Module.

To better understand what you are trying to achieve, why the object should have behaviour attached? What's the use case?

cipolleschi avatar Jan 17 '23 13:01 cipolleschi

Why these objects are meant to be data objects?

I solved my problem declaring a function in the spec that returns Object.

In native code this is a jsi::HostObject with methods handled in the object's native get method.

Then I had to force a cast from Object to some interface declared in another TypeScript file.

I cannot understand why it can't be declared correctly in the TypeScript' spec file.

asfernandes avatar Jan 18 '23 01:01 asfernandes

I cannot understand why it can't be declared correctly in the TypeScript' spec file.

You can declare it correctly in the TypeSpec file. You may have object with behavior, in TypeScript. However, the spec files are used to generate objects in the Native platform code, and we can't generate the behavior. It would imply that Codegen should be able to read the method body and to translate it in platform code, which is not easy and probably not even worth while.

Your approach works, but you have to give up type safety: in fact you had to cast your object to what you needed. That's is doable but a bit risky, as casting is usually not advisable.

Does it make sense?

What could be done is to have only the interface declared and codegen'd in platform code, but then we would have to create a mechanism to implement the behavior without the risk that codegen override those files. As you can see, the problem is more complex than what it seems at first sight.

cipolleschi avatar Jan 30 '23 11:01 cipolleschi