The argument provided is a string type, which cannot be assigned to a parameter expecting an object with a 'results' property of type string

When attempting to pass the result.nativeEvent.message to another function, I am encountering the error: Argument of type 'string' is not assignable to parameter of type '{ results: string; } on

onUnityMessageController(result.nativeEvent.message)
.

I'm puzzled as to why a 'string' cannot be assigned to a 'string' parameter.

Unity.tsx

import React, { useRef, useEffect } from 'react';
import UnityView from '@azesmway/react-native-unity';
import { View, Button, NativeSyntheticEvent } from 'react-native';
import { CommonActions } from '@react-navigation/native';

interface IMessage {
  gameObject: string;
  methodName: string;
  message: string;
}

const Unity = ({ navigation, route }: { navigation: undefined, route: any }) => {
  const unityRef = useRef<UnityView>(null);

  const shape = route.params.shape;
  const color = route.params.color;

  const parsedMess = JSON.stringify(route.params);
  console.log(parsedMess);

  const closeUnity = () => {
    unityRef.current?.unloadUnity();
    navigation.goBack();
  }

  useEffect(() => {
    if (unityRef?.current) {
      const message: IMessage = {
        gameObject: 'gameObject',
        methodName: 'methodName',
        message: 'message',
      };
      unityRef.current.postMessage(message.gameObject, message.methodName, message.message);
      if (shape != null && color != null) unityRef.current.postMessage("SceneManager", "startUnity", shape + ";" + color);
    }
  }, [shape, color]);



  const onUnityMessageController = ({ results }: { results: string }) => {
    console.log('onUnityMessage', results);
  }

  return (
    <View style={{ flex: 1 }}>
      <UnityView
        ref={unityRef}
        style={{ flex: 1 }}
        onUnityMessage={(result) => { onUnityMessageController(result.nativeEvent.message), console.log(result.nativeEvent.message) }} />
      <Button title="Close Unity Screen" onPress={() => closeUnity()} />
    </View >
  );
};

export default Unity;

The result.nativeEvent.message originates from:

import React from 'react';
import { NativeSyntheticEvent, ViewStyle } from 'react-native';
interface UnityMessage {
    message: string;
}
declare type ReactNativeUnityViewProps = {
    androidKeepPlayerMounted?: boolean;
    fullScreen?: boolean;
    onUnityMessage?: (event: NativeSyntheticEvent<UnityMessage>) => void;
    onPlayerUnload?: (event: NativeSyntheticEvent<void>) => void;
    onPlayerQuit?: (event: NativeSyntheticEvent<void>) => void;
    style?: ViewStyle;
};
export default class UnityView extends React.Component<ReactNativeUnityViewProps> {
    static defaultProps: {};
    constructor(props: ReactNativeUnityViewProps);
    postMessage(gameObject: string, methodName: string, message: string): void;
    unloadUnity(): void;
    pauseUnity(pause: boolean): void;
    resumeUnity(): void;
    private getCommand;
    private getProps;
    componentWillUnmount(): void;
    render(): JSX.Element;
}
export { };

Answer №1

Instead of passing a simple string as an argument to the function onUnityMessageController, you are expecting an object type check. To resolve this, adjust your function like so:

  const onUnityMessageController = (data: string) => {
    console.log('onUnityMessage', data);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Precise object mapping with Redux and Typescript

In my redux slice, I have defined a MyState interface with the following structure: interface MyState { key1: string, key2: boolean, key3: number, } There is an action named set which has this implementation: set: (state: MyState, action: PayloadAct ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

What is the process for dynamically loading a concrete implementation and customizing object creation through parameterization?

Concern I am currently developing a Chrome Extension that is capable of receiving commands and is built using TypeScript. My objective is to separate out concrete implementations of a class into individual files that can be loaded dynamically. Illustrat ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Can you guide me on incorporating a date input with ngModel?

I have a date input field set up as follows: <input [(ngModel)]="value" type="text" class="form-control"> Can someone explain how I can display and submit the value correctly? The user's input should be formatted as dd/MM/yyyy, while t ...

What is the process for an Angular Component to receive a return object from a service following an HTTP

I am currently working with angular 4. Is there a way to retrieve an object from a service in this framework? export class LoginRequest { username : string; password : string; } export class LoginResponse { token : string; message : string; sta ...

Using React with an Array of Promises in Typescript

I have a function that looks like this: function queryProposals(hash:string) { let result = api?.query.backgroundCouncil.proposalOf( hash,(data1:any)=>{ let injectedData = data1.toPrimitive().args.account as InjectedAccou ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Calculate the sum of elements within an array

I've been attempting to calculate the sum of values in an array based on different levels, but so far I haven't had much success. Here are the data I'm working with (stored in a variable called totalByLevel): https://i.stack.imgur.com/rOP9 ...

Leveraging AngularJS services within an Angular service

I am currently in the process of transitioning my AngularJS application to Angular. To facilitate this transition, I plan to create a hybrid application that combines both frameworks until the conversion is complete. However, I have encountered an issue wi ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

script code to limit selection of dates within a predefined range

I'm seeking assistance to limit my customers from selecting a date beyond 10 days in advance. Although I previously had a code that functioned properly when there were more than 10 days left in the current month, it is now ineffective. This is becaus ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on h ...

"Creating an array object in the state of Reactjs - a step-by-step

As I am delving into the world of ReactJS, I am learning about changing state within this framework. One challenge I encountered was initializing an array object in state with an unknown length and updating it later using setState. Let me share the snippet ...

Image not found in next.js

Working Environment ・ next.js ・ typescript ・ styled-components I uploaded the image in the folder inside pages, but it is not showing up. Why is that? // package.json   { "name": "nextapp", "version": &qu ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

Error encountered when upgrading to Material-UI v5 rc.0 with typescript

After updating my material-ui to version v5-rc.0, I decided to implement styled-components. However, as I was working on my Component.styles.ts file, I encountered an error: The inferred type of 'StyledStepper' cannot be named without a referen ...