Exploring the World of Geometry with Three.js and TypeScript

How can I correctly define types for Mesh Vertices and Faces?

In my initial attempt, I decided to create a new Mesh object. However, when attempting to access Vertices and Faces from the geometry property, I encountered a few errors:

const material = new THREE.MeshLambertMaterial({color: 0x00ff00});
const geometry = new THREE.Geometry();
const newMesh = new THREE.Mesh(geometry, material);
scene.add(newMesh);

const { vertices, faces } = newMesh.geometry;
// Issue: Property 'vertices' is missing on type 'BufferGeometry | Geometry'
// Issue: Property 'faces' is missing on type 'Geometry | BufferGeometry'.

newMesh.geometry.colorsNeedUpdate = true;
// Problem: Property 'colorsNeedUpdate' does not exist on type 'Geometry | BufferGeometry'.

In a different scenario, I obtained a Mesh object from the Scene but faced a new error:

const mesh = scene.getObjectByName('boxMesh');
const geometry = mesh.geometry; 
// Error: Property 'geometry' does not exist on type 'Object3D'.

Answer №1

When you access the geometry through the mesh (newMesh.geometry), you will receive the typed geometry similar to the geometry property found in the Mesh class. It seems that this property can support two different types of geometry, resulting in a union: Geometry | BufferGeometry.

If you are certain about the type of geometry being used, you can simply assert the type of the property value:

const { vertices, faces } = <THREE.Geometry>newMesh.geometry;

If you are unsure about the type of geometry, you will need some conditional logic, such as:

const geometry = newMesh.geometry;
if (geometry instanceof THREE.Geometry)
    // The type of geometry will be Geometry here
else
    // The type of geometry will be BufferGeometry here

In the second scenario, when using getObjectByName, it always returns objects of the most basic type, Object3D. In this case, you also need to assert the type of the result accordingly.

// Assuming that the object named boxMesh is a Mesh...
// The <any> assertion helps prevent additional type errors.
const mesh = <THREE.Mesh><any>scene.getObjectByName('boxMesh');

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

Typedoc does not create documentation for modules that are imported

Whenever I generate documentation with TypeDoc, I am encountering an issue where imported files come up empty. If I add a class to the file specified in entryPoints, I get documentation for that specific class. However, the imported files show no document ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

Converting Javascript tools into Typescript

I'm currently in the process of migrating my Ionic1 project to Ionic2, and it's been quite an interesting journey so far! One challenge that I'm facing is how to transfer a lengthy list of utility functions written in JavaScript, like CmToFe ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

Having trouble getting Jest to manually mock in Nestjs?

When setting up a mock service like this: // /catalogue/__mock__/catalogue.service.ts export const CatalogueService = jest.fn().mockImplementation(() => { return { filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filt ...

Tips for securely passing props based on conditions to a functional component in React

I came across this situation: const enum Tag { Friday: 'Friday', Planning: 'Planning' } type Props = { tag: Tag, // tour: (location: string) => void, // time: (date: Date) => void, } const Child: React.FC<Props> = ...

How can a parent component update a child component's prop value in VUE?

I'm facing an issue with managing dynamic props in Vue with TypeScript. Below is my parent component: <script setup lang="ts"> const friends = [ { id: "emanuel", name: "Emanuella e", phone: "08788 ...

Removing data based on various criteria in Prisma

While I understand that the where clause in Prisma requires a unique input for its delete operation, I have utilized the @@unique function to ensure that multiple conditions need to be columns together and must be unique. However, I am struggling with how ...

Instructions for including a class are ineffective

I am trying to dynamically add a class to a div based on two conditions. To achieve this, I have created a custom directive as shown below: import { Directive, HostBinding, Input } from '@angular/core'; @Directive({ selector: '[confirmdia ...

Using Three.js BVHLoader in React/React Native applications

I am currently working on developing an application or website for displaying BVH animation. I came across a BVHLoader example in Three.js that I found interesting: BVHLoader example. I am aware that React and React Native can be used with Three.js as we ...

Locate the intersection point of an arc using three.js

I am working with a unique type of geometry called TorusGeometry. To achieve what I need, I must translate this geometry to a specific point labeled as C, which is the intersection point of perpendicular lines drawn from the center points of both ends labe ...

Different categories of properties within a generic function

I'm attempting to modify certain fields of my object using field names. Here is the code snippet I have written: interface Foo { a: number[], b: string[], } type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] } function test<T ex ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

The issue of "ReferenceError: Cannot access '<Entity>' before initialization" occurs when using a OneToMany relationship with TypeORM

There are two main actors involved in this scenario: User and Habit. The relationship between them is defined by a OneToMany connection from User to Habit, and vice versa with a ManyToOne. User Entity import {Entity, PrimaryGeneratedColumn, Column, Creat ...

Ways to alter the Three.js file

Just downloaded a code from Github that I want to modify. The goal is to adjust the code so that the Earth can be moved by using arrow keys on the keyboard instead of the mouse. How can I go about modifying the code to achieve this? Thank you for your assi ...

Consecutive API requests within React context

When I'm developing locally, I encounter the error message Error: Rendered more hooks than during the previous render. in my application when refreshing the page. I suspect this is happening because I am making two calls within my provider. The first ...

NextJS: Route Handler encountering Method Not Allowed (405) error when trying to redirect

Current NextJs version is 13.4.3 I have set up a route handler to capture POST requests. For more information on route handlers, please refer to the documentation at [https://nextjs.org/docs/app/building-your-application/routing/router-handlers] In this ...

Creating a TypeScript definition file to allow instantiation of a module

I'm encountering an issue with creating a declaration file for an existing module. When using JavaScript, the module is imported using the following syntax: var Library = require('thirdpartylibs'); var libInstance = new Library(); I have ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...