What properties are missing from Three.js Object3D - isMesh, Material, and Geometry?

Currently, I am working with three.js version r97 and Angular 7.

While I can successfully run and serve the application locally, I encounter type errors when attempting to build for production.

Error TS2339: Property 'isMesh' does not exist on type 'Object3D'.

Error TS2339: Property 'material' does not exist on type 'Object3D'.

Error TS2339: Property 'geometry' does not exist on type 'Object3D'.

These errors occur after the object is loaded and I start traversing its parts.

The issue lies in child.isMesh and the subsequent modifications made to the child object which are generating errors.

Being new to TypeScript, I'm uncertain if there's a more effective way to handle these manipulations. As far as I can tell, forcing a production build seems to be out of reach. Any guidance or suggestions on resolving this problem would be greatly appreciated.

this.loader = new THREE.FBXLoader();
      this.loader.load('assets/models/C4D_Export.fbx', object => {

          object.traverse( child => {

              if( child.type == "Group"){
                  child.name = 'ToolGroup';
              }
              if ( child.isMesh ) {

                  const oldMat = child.material;
                  //CONVERT MATERIAL TO STANDARD MATERIAL.
                  child.material = new THREE.MeshStandardMaterial({
                      color: oldMat.color,
                      map: oldMat.map,
                  });

                  child.castShadow = true;
                  child.receiveShadow = true;
                  child.material.combine = THREE.MixOperation;
                  child.material.envMap = envMap;
                  child.material.shininess=10;
                  child.material.refractionRatio=1;
                  child.material.reflectivity=1;
                  //child.material.normalMap = texture;
                  //child.material.normalMapType = 0;
                  child.material.metalness=1;
                  child.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(5, 0, 0));
                  //child.material.color.setHex( 0xffffff );

                  var f2 = gui.addFolder('Position'+child.name);
                      f2.add(controller, 'positionX', -50, 50).onChange( function() {
                         child.position.x = (controller.positionX);
                      });
                      f2.add(controller, 'positionY', -50, 50).onChange( function() {
                         child.position.y = (controller.positionY);
                      });
                      f2.add(controller, 'positionZ', -50, 50).onChange( function() {
                         child.position.z = (controller.positionZ);
                      });

                  var sphereAxis = new THREE.AxesHelper(200);
                  child.add(sphereAxis);

              }

          });

          object.position.y = -20;
          object.scale.set(1,1,1);
          object.rotation.z = (-90*(Math.PI/180));
          objholder.add(object);


      });

To address the issue, I attempted to create an interface for Object3D with defined properties:

interface Object3D{
    isMesh?: any,
    geometry?: any,
    material?: any,
}

Unfortunately, the error persists despite this modification.

Edit: Update 2

A temporary solution that seems to work is adding //@ts-ignore above each problematic line causing errors. Although unsure if this is considered bad practice, it resolves the issue for now.

Answer №1

Your TypeScript development setup seems to be configured differently from your production setup, which is likely why you're encountering an error during build but not when compiling locally for development. (To clarify, the error is accurate because child should be an Object3D, which doesn't have the .isMesh property.)

Instead of using //@ts-ignore, consider specifying the type of child explicitly:

if ( child.isMesh ) // Error: .isMesh property does not exist in Object3D

if ( (<any> child).isMesh ) // No error, but lacks type-checking with <any>

if ( (<THREE.Mesh> child).isMesh ) // No error and grants access to Mesh properties

For more information on type assertions, refer to the TS documentation.

Answer №2

To perform an assertion check, you can implement a function similar to the following:

export function isWidgetType(object?: Object3D): object is THREE.Widget {
  return object?.type === 'Widget'
}

Then apply it in the code like this:

if (isWidgetType(item) && item.isWidget) {
  // item is a Widget instance
}

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

Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values: { "message.key": "First value is {{0}} and se ...

The rendering with Three.js has finished successfully

I'm curious, is there a way to determine when the object has finished rendering? While I've seen a progress bar in one example, I'm seeking a straightforward and uncomplicated illustration. So far, I've searched through the loader I&apo ...

Having Trouble Adding Details to a New Cart for a User in Angular and MongoDB - What's Going On?

After working on an E-Commerce site for a while, I hit a roadblock. Despite taking a break and coming back with determination, I can't seem to resolve the issue at hand. The application features registration, login, product search, and a popup window ...

What could be causing my THREE.js Documentation Box to malfunction?

I am a newcomer trying to get the hang of THREE.js. I delved into the THREE.js Documentation and attempted to implement the code, but when I loaded my HTML page, it appeared blank. I am at a loss for what to do next. I utilized Visual Studio Code for codin ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

Using optional chaining on the left side in JavaScript is a convenient feature

Can the optional chaining operator be used on the left side of an assignment (=) in JavaScript? const building = {} building?.floor?.apartment?.number = 3; // Is this functionality supported? ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

AngularJS UI-Router in hybrid mode fails to recognize routes upon initial page load or reload

It appears that when using the @ui-router/angular-hybrid, routes registered within an ng2+ module are not being recognized during the initial load or reload. However, these same routes work fine when accessed by directly typing the URL. I have followed th ...

Utilizing custom colors in a Typescript/React/MUI Button component to enhance its design

How can I apply custom colors to the Button component without getting an error? Are there any possible solutions for this issue? I followed the module augmentation approach outlined in the documentation, but the problem persists: https://mui.com/material ...

Error encountered with object.map() function - what fundamental concept am I missing?

Could someone lend me a fresh set of eyes on this... The React Component is fetching data from MariaDB using a useEffect() hook. The data is retrieved successfully without any errors, and the console.log shows the correct data (refer to the image below). ...

The supabase signup function keeps showing me the message "Anonymous sign-ins are disabled." Can anyone help me understand why this is happening?

I'm currently in the process of setting up authentication in Next.js with supabase, but encountering an issue when attempting to execute the signUp function. The error message I'm seeing is: Anonymous sign-ins are disabled Below is the snippet o ...

What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below: export class HomeComponent { constructor() { this.loadDynamicScript(); } public loadDynamicScript() { var script = document.createElement(&a ...

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Creating a material texture with file api in three.js is a straightforward process

I have a vision to create a cutting-edge model browser that allows users to handpick models and textures themselves. In order to achieve this, I am utilizing the File API for smooth file handling. My approach involves using two separate file inputs for rec ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...