What's the best way to define the data types for a component that utilizes the set function?

This code snippet seems to be functional, but there are some issues with the types that need to be resolved before it can be compiled successfully.

Here is the code in question:

function SpotlightElement(props: JSX.IntrinsicElements['spotLight']) {
  return (
    <group ref={group}>
      <SpotLight ref={**set**} />
    </group>
  )
}

export default function MovingSpot() {
  const [depthBuffer, setDepth] = useState()
  return (
    <>
      <DepthBuffer ref={setDepth} size={512} />
      <SpotlightElement **depthBuffer**={depthBuffer} />
    </>
  )
}

My concern lies with how TypeScript interprets the usage of the ref for the SpotLight component being retrieved from the set function. Currently, it is assuming that the ref brings the component itself instead of the configuring function. This results in the error: Type 'Dispatch' is not assignable to type 'Ref | undefined'.

Additionally, if the props attribute from the SpotLightElement function is supposed to be declared as JSX.IntrinsicElements of 'group', which type should be used instead? The depthBuffer property does not seem to exist in the spotLight props defined in three-types.d.ts:

Property 'depthBuffer' does not exist on type 'IntrinsicAttributes & Omit<Node<Group, typeof Group>, NonFunctionKeys<{ position?: Vector3 | undefined; up?: Vector3 | undefined; scale?: Vector3 | undefined; ... 4 more ...; dispose?: (() => void) | ... 1 more ... | undefined; }>> & { ...; } & EventHandlers'.

Any assistance or guidance on resolving these issues would be greatly appreciated. Thank you!!!

Answer №1

Appreciation for your responses. With guidance from the creators of drei, I decided to implement THREE.SpotLight for my project. To achieve this, I made adjustments to the component provided by three and also introduced the SpotLightProps type. Below is the final implementation:

type SpotLightProps = JSX.IntrinsicElements['spotLight'] & {
  depthBuffer?: DepthTexture
  attenuation?: number
  anglePower?: number
  color?: string | number
}

const vec = new Vector3()
function SpotlightElement(props: SpotLightProps, ref: React.ForwardedRef<SpotLightImpl>) {
  const group = useRef<THREE.Group>(null!)
  const [light, set] = useState<THREE.SpotLight>(null!)
  const viewport = useThree((state) => state.viewport)
  useFrame((state) => {
    group.current.position.lerp(vec.set(state.mouse.x, state.mouse.y, 0), 0.1)
    light.target.position.lerp(vec.set((state.mouse.x * viewport.width) / 2, (state.mouse.y * viewport.height) / 2, 0), 0.1)
  })
  return (
    <group ref={group}>
      <spotLight ref={set} />
      {light && <primitive object={light.target} />}
    </group>
  )
}

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

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...

Issue with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

Storing application state using rxjs observables in an Angular application

I'm looking to implement user status storage in an Angular service. Here is the code snippet I currently have: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() expo ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

Unexpected color is displayed when using Three.js setHSL() method

setColorUsingHSL(hue, saturation, lightness) - Use this function to set the color based on provided HSL values. Remember, these values should be between 0 and 1. When I call material.color.setColorUsingHSL(0.5, 1, 0.5), why am I seeing cyan instead of yel ...

Is there a method to retrieve and organize all routes and corresponding endpoints in a NestJS application?

When it comes to writing middleware to process requests, I am faced with the issue of excluding certain paths without having to hardcode them manually. To tackle this problem, I came up with an innovative solution: My plan is to create a special decorator ...

Encountering a White Screen Error while attempting to generate a GLB file using a jsx file in my React Three.js

I've encountered a problem while trying to incorporate a glb file with react three and three.js in order to display a 3D model on my website. Although various tutorials seem to work flawlessly, I'm facing issues getting it to function correctly ...

Encountering an Unknown Error when attempting to retrieve a response using Angular's httpClient with

The Service.ts file contains the following code: public welcome(token: any){ let tokenString = "Bearer "+token console.log("tokenString is: "+tokenString) let header = new HttpHeaders().set("Authorization",tokenSt ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Access the most up-to-date information through the API URL

Objective: Whenever the 'Test' Button is clicked, new data must be fetched from the backend using the API link and displayed on the modal form. Issue: If text in the input box is changed or deleted, then the modal is closed and the 'Tes ...

When using Styled Components with TypeScript, you may encounter the error message "No overload matches

Recently, I've delved into Style Components in my journey to create a weather app using React Native. In the past, I would typically resort to CSS modules for styling, but it appears that this approach is not feasible for mobile development. Below is ...

Renderer's Delayed Electron Loading

I am in the process of developing a Electron application using TypeScript and React. This application serves as an account manager, allowing users to retrieve and view data for specific accounts. However, I have encountered an issue with the ipcMain.on(&a ...

Generating HTML components dynamically using strings in TypeScript

Is there a way to define a prop that can accept either a ComponentType or a string? Consider the code snippet below. interface MyComponentProps { Component: React.ComponentType } const MyComponent: React.FC<PropsWithChildren<MyComponentProps> ...

Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid. I wondered if there was something ...

Can a React.tsx project be developed as a standalone application?

As a student, I have a question to ask. My school project involves creating a program that performs specific tasks related to boats. We are all most comfortable with React.tsx as the programming language, but we are unsure if it is possible to create a st ...

Error message: The specified type is incomplete and lacks certain properties, according to Typescript

I'm encountering an error that's hindering the deployment of my website on Vercel. Any assistance would be greatly appreciated. Usually, I retrieve the pageInfo data from Sanity and use it on my website. The issue lies in this peculiar TS error t ...