Home > Software engineering >  Property 'rotation' does not exist on type 'never' in react typescript
Property 'rotation' does not exist on type 'never' in react typescript

Time:11-04

I am starting learning "React Three Fiber" with TypeScript, but when I started my journey, I got stuck with this problem. I've searched a lot on internet but didn't find my answer.

import React from "react";
import { Canvas, useFrame } from "@react-three/fiber";


const AnimatedBox() {
  const meshRef = useRef();
      useFrame(()=>{
          console.log("hi");
          if(meshRef.current){
          meshRef.current.rotation  = 0.01;


          }
      });
    
    return (

          <mesh ref = {meshRef} scale={[0.5, 0.5 ,0.5]}>
            <boxGeometry />
            <meshStandardMaterial  />

          </mesh>

    );
  }

export default function App() {
  return (
    <div className="App">
      <Canvas>
        <AnimatedBox />
        <ambientLight intensity={0.1} />
        <directionalLight />
      </Canvas>
    </div>
  );
}

Every time I run this code I got this error:

Property 'rotation' does not exist on type 'never'.

CodePudding user response:

Add a type to useRef

const meshRef = useRef<HTMLElement>()

CodePudding user response:

Three's Documentation explains how to tackle this issue

React's useRef won't automatically infer types despite pointing it to a typed ref.

You can type the ref yourself by passing an type through useRef's generics

The exclamation mark is a non-null assertion that will let TS know that ref.current is defined when we access it in effects.

In your case that would be something like:

import { Mesh } from 'three'

const meshRef = useRef<Mesh>(null!)
  • Related