简体   繁体   中英

error TS2345: Argument of type '{ x: number; y: number; z: number; }' is not assignable to parameter of type 'string'

I am trying to create a-image dynamically with the values received. But somehow I am getting below error while setting the position attribute of the imgObj(code below)

xpos, ypos and zpos contains string floating values like xpos = "-0.2", ypos="-0.1", zpos="0.2"

var imgObj = document.createElement("a-image");
imgObj.setAttribute("src",'url(' + $event.src + ')');
//imgObj.setAttribute("position",{x:0,y:0,z:0})
imgObj.setAttribute('position',{x:xpos, y:ypos, z:zpos});

Any idea or pointers will help...thanks

If you were not using aframe, that would have been the correct behaviour from TypeScript, because in DOM / HTML only world, you'd get unexpected results from giving an object as the value of setAttribute .

To tell TypeScript about the extra capabilities aframe adds, you can install the aframe typings:

npm install -D @types/aframe

This will add the typings that say the setAttribute can take an object with x,y,z numbers, when the the attribute is

Quoting from the typings https://unpkg.com/@types/aframe@0.8.0/index.d.ts :

export interface Coordinate {
    x: number;
    y: number;
    z: number;
}

Then lower in the file:

setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;

So, looks like it should do it.

Final thought

It's worth noting that using setAttribute for this is not recommended by aframe, as shown in their documentation: https://aframe.io/docs/0.8.0/components/position.html

For performance and ergonomics, we recommend updating position directly via the three.js Object3D .position Vector3 versus via .setAttribute.

This method is easier because we have access to all the Vector3 utilities, and faster by skipping .setAttribute overhead and not needing to create an object to set rotation:

I guess the solution is don't use Typescript. It doesn't expect DOM methods to be overridden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM