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

Error: Vercel deployment of Next.Js app fails due to undefined localStorage

Encountering the issue ReferenceError: localStorage is not defined when attempting to deploy my Next.JS app on Vercel. const NewReserve: React.FC = () => { const setValue = (key: string, value: string) => { return localStorage.setItem(key, val ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

Unable to generate a store using reducer in TypeScript and Redux

I am having trouble creating a store using Redux and TypeScript. Here is my actions.js file: import { Action } from 'redux'; export interface ITodoAction extends Action { todo:string; } export const ADD_TODO:string = 'ADD_TODO'; ...

Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options. I understand how the Bootstrap modal opens and closes: The display pro ...

What steps can I take to resolve the "Unable to call a potentially 'undefined' object" error?

I'm currently working with CreateContext in Typescript and I have encountered a problem in the code that I can't seem to resolve. I am trying to use typesafe TX to provide state and dispatch (via useReducer) in a component hierarchy. Here is the ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Utilizing TypeScript with Sequelize for the Repository Design Pattern

I am in the process of converting my Express API Template to TypeScript, and I am encountering difficulties with the repositories. In JavaScript, the approach would be like this: export default class BaseRepository { async all() { return th ...

Tips on integrating Cheerio with Angular framework

My Angular website is encountering errors in Google Dev Tools's console when I utilize a Cheerio method load('<h2 class="title">Hello world</h2>'); as per the instructions on the Github page. This application is fresh, and the s ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...

What is the best way to filter an array of objects and store the results in a new variable list using typescript?

On the lookout for male objects in this list. list=[ { id: 1, name: "Sam", sex: "M"}, { id: 2, name: "Jane", sex: "F"}, { id: 3, name: "Mark", sex: "M"}, { id: 4, name: "Mary, sex: "F& ...

How can Typescript generics verify the value type for a specific key in a generic object?

I am facing an issue with a function called sortData. This function takes in a key and is designed to sort an array of objects based on the values for that key: function compare(v1: string | number, v2: string | number) { return (v1 < v2 ? -1 : v1 > ...

Is it possible to pass parameters from a base class's constructor to a child class?

I'm facing an issue with my base (generic) classes where the properties are initialized in the constructor. Whenever I try to extend these classes to create more specific ones, I find myself repeating the same parameters from the base class's con ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

Error: Cookie cannot be set due to headers already being sent

Here lies my code snippet import { Request, Response } from "express"; import { database } from "firebase-admin"; async function updateAccessToken( req: Request, res: Response, db: database.Database ) { try { await db ...

Issue encountered during mozjpeg installation - unable to locate mozjpeg's cjpeg in the vendor directory due to

During my attempt to set up mozjpeg within a Docker container running NAME="Alpine Linux" ID=alpine VERSION_ID=3.11.7 PRETTY_NAME="Alpine Linux v3.11" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpin ...

Ensure thorough validation of the JSON.parsed data in TypeScript

Currently, I am developing a small module for Angular and I have encountered an issue regarding the condition where I verify my JSON.parsed data. read(): Position|null { try { ... let parsedData = JSON.parse(data); if (parsed ...

How to show the current week using React Native

Looking to show the current week of the month in a specific format using react-native: (Week 2: 05.10 - 11.10) (for example, displaying week 2 of the current month) Any ideas on how to make this happen? I'm aware of packages like momentjs that can ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...