繁体   English   中英

错误TS2345:类型为'{x:number; y:数字; z:数字; }'不可分配给'string'类型的参数

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

我正在尝试使用接收到的值动态创建一个图像。 但是以某种方式我在设置imgObj的position属性时出现下面的错误(下面的代码)

xpos, yposzpos包含字符串浮动值,例如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});

任何想法或建议都会有所帮助...谢谢

如果您没有使用Aframe,那将是TypeScript的正确行为,因为在仅DOM / HTML的世界中,将对象作为setAttribute的值会得到意外的结果。

要告知TypeScript aframe所增加的额外功能,您可以安装aframe类型:

npm install -D @types/aframe

当属性为时,这将添加如下类型: setAttribute可以接受带有x,y,z数字的对象。

从键入内容引用https://unpkg.com/@types/aframe@0.8.0/index.d.ts

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

然后在文件中降低:

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

因此,看起来应该这样做。

最后的想法

值得注意的是,aframe不建议为此使用setAttribute ,如其文档中所示: https ://aframe.io/docs/0.8.0/components/position.html

为了提高性能和人机工程学,我们建议直接通过three.js Object3D .position Vector3与.setAttribute来更新位置。

此方法更容易,因为我们可以访问所有Vector3实用程序,并且通过跳过.setAttribute开销并且不需要创建对象来设置旋转即可更快地实现:

我想解决方案是不使用Typescript。 它不希望DOM方法被覆盖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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