The method useImperativeHandle encounters an issue: it cannot find the property 'ref' within the type 'IntrinsicAttributes & ResultsConnectedProps'

I encountered an issue while attempting to pass a ref to a forwardedRef component. Below is the code for the forwardRef component:

interface ResultsConnectedProps {
  sql: string;
}

export const ResultsConnected: FC<ResultsConnectedProps> = forwardRef(({ sql }, ref) => {
  const [lastUpdateAt, setLastUpdateAt] = useState(0);

  useImperativeHandle(ref, () => ({
    runQuery: () => {
      setLastUpdateAt(Date.now());
    },
  }));

 ...
});

After that, I tried to declare it in a parent component like this:

const resultsRef = useRef(null);

...

<ResultsConnected ref={resultsRef} sql={sql} />

This resulted in the following error message:

Type '{ ref: MutableRefObject<null>; sql: string; }' is not assignable to type 'IntrinsicAttributes & ResultsConnectedProps'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & ResultsConnectedProps'.ts(2322)
(property) ref: React.MutableRefObject<null>

Answer №1

const ResultsComponent: FC<ResultsComponentProps>

When you specify the type as FC<ResultsComponentProps>, all information about the ref is lost. It's better to use forwardRef which retains type information and is written as a generic. I suggest implementing it like this:

interface ResultsComponentProps {
  query: string;
}

interface ResultsComponentRef {
  executeQuery: () => void;
}

export const ResultsComponent = forwardRef<ResultsComponentRef, ResultsComponentProps>(
  ({ query }, ref) => {
    const [lastUpdatedTime, setLastUpdatedTime] = useState(0);

    useImperativeHandle(ref, () => ({
      executeQuery: () => {
        setLastUpdatedTime(Date.now());
      },
    }));

    ...
  }
);

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

What is preventing TypeScript from resolving assignment in object destructuring?

Consider the code snippet below: interface Foo { a?: number b?: number } function foo(options?: Foo) { const { a, // <-- error here b = a } = (options ?? {}) return [a, b] } Why does this code result in the followi ...

Change icons in Ionic 5 when selecting a tab

How can I change my tab icons to outline when not selected and filled when selected? The Ionic 5 Tabs documentation mentions a getSelected() method, but lacks examples on its usage. I plan to utilize the ionTabsDidChange event to detect tab clicks, then ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

What could be causing the need for RxJs TypeScript files to be requested exclusively when my website is hosted on IIS?

When I develop my site using Visual Studio / IIS Express, everything runs smoothly without any unusual requests or 404 errors. However, once I publish the site to IIS and try to run it, I start receiving multiple requests for typescript files (.ts), prima ...

Typescript and React: Unraveling the intricacies of complex

Is it possible to define custom types verified by a function in Typescript/React? Instead of using a simple 'string' type, I envision using a regex expression: interface Verify { email: /.+@.*\.com/g; } The specific regex above might not ...

Convert an object to nested JSON in Angular 5

I am struggling with using Angular 5 HttpClient to send a post request because I am having trouble casting an object to nested JSON. For instance, I have the following class: export class Team { members: Person[]; constructor(members: Person[]) ...

Using TypeScript with React Router to access the isActive property on NavLink

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55273034362178273a2021302778313a3815637b6167">[email protected]</a> and have implemented the following react component: import { Link as Nav ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

Connect AngularFire to a specific object

I'm facing an issue with my Users.class where I need it to automatically map or bind after fetching data from Firebase. I've been trying to search for the right term but haven't found any information yet. import { Component, OnInit } from & ...

Issue with implicitly assigning 'any' type to overloaded variadic generic function

We have some code snippets for you to review: export type actions = { abort: () => void; back: () => void; next: () => void; resume: () => void; }; class Sabar { public use<T1>(fn: (arg1: T1, ctx: object, actions: actions) =&g ...

Tips on pairing elements from a ngFor processed list with another list using ngIf

If we have a list such as the one shown below: elements = [ { id: 1, name: "one" }, { id: 3, name: "three" }, { id: 5, name: "five" }, { id: 6, name: "six" }, ]; lists = [ { id: 5, name: "five" }, { id: 9, ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

Typescript fastify route handler for handling requests and responses

Can someone please explain to me the request and response handler types used in fastify? Currently, I am utilizing 'any' without knowing the specific types, which has triggered a warning from the TypeScript eslint: fastify.post('/ac', ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

Typescript in Firebase Functions organization

Struggling with typescript organization in my firebase functions. I'm fine keeping trigger functions in index.ts for now, but need help organizing other utility functions elsewhere. Current index.ts setup: import * as functions from 'firebase-f ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

In Typescript, is it possible to utilize the value from a particular key in a type declaration as the type for another key within the same declaration?

Consider a scenario where I am designing a Variable type that includes a key named type with a value of type string. Is there a method to extract the value from the type key and utilize it as the type for another key within the declaration, without resorti ...