TypeCasting Meshes and Materials

This is probably more of a TypeScript question (because I’m new to TypeScript), but I’m having trouble managing the AbstractMeshes and Materials that are returned when you load in an asset from .glb or .babylon.

In terms of materials, I am trying to apply PBRMaterial settings to the material, because I know they are PBRMaterials, but I cannot because it says the property is not a value of type Material.
I’m having the same issue with AbstractMeshes, where I am trying to add the meshes to a HighlightLayer, but the HighlightLayer requires a Mesh, not AbstractMesh.

The thing is, when I verify if the meshes[i] instanceof Mesh or material[i] instanceof PBRMaterial, they both come back as true everytime, but when I try to set a property of PBRMaterial or Mesh to that object, I get a compile error in the IDE (VS Code).

To solve this (which I feel like is probably over-solving it, since the object types seem set), I am trying to down-cast the objects via if(materials[i].getClassName() == “PBRMaterial”) {materials[i] = materials[i] as PBRMaterial;} and if(meshes[i].getClassName() == “Mesh”) {meshes[i] = meshes[i] as Mesh;}, but when I try to set the properties, I’m still getting an error flag in VS Code that the meshes[i] and materials[i] objects are still of the more abstract type, respectively. I’ve also tried using materials[i].metallic = …

How can I down-cast an object without having to replace it with a cloned copy entirely, which could get expensive, so that I can apply the correct settings to them?

Thanks!

The problem with doing something like materials[i] = materials[i] as PBRMaterial is that your materials array is still of type Material[]. When you access things in the future from that array, each materials[i] will still be accessed only as a Material as far as TypeScript is concerned.

Doing something like const material = materials[i] as PBRMaterial will allow you to set material.metallic. You can also set the property by temporarily casting: (materials[i] as PBRMaterial).metallic.

1 Like

that worked, thanks!