【问题标题】:typescript+THREE: Class 'Vertex' incorrectly extends base class 'Vector3'打字稿+三:类“顶点”错误地扩展了基类“Vector3”
【发布时间】:2017-11-04 00:19:36
【问题描述】:

使用带有@types/three 定义的三个库

试图让自己的类扩展 THREE.Vector3

export class Vertex extends THREE.Vector3  {

constructor(
    x:number,
    y:number,
    z:number,
    public normal:THREE.Vector3 = new THREE.Vector3(),
    public uv:THREE.Vector2 = new THREE.Vector2())
{
  super(x,y,z);
}

clone():Vertex
{
  return new Vertex(this.x, this.y, this.z, this.normal.clone(), this.uv.clone());
}

但出现错误:

TS2415: Class 'Vertex' incorrectly extends base class 'Vector3'.

“克隆”属性的类型不兼容。 类型 '() => Vertex' 不可分配给类型 '() => this'。 类型“顶点”不可分配给类型“this”。

在三个定义vector3中定义为:

export class Vector3 implements Vector {
constructor(x?: number, y?: number, z?: number);

x: number;
y: number;
z: number;
clone(): this;

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    看起来Vector3clone() 方法使用polymorphic this 作为其返回类型。这意味着Vector3 的每个子类/实现都需要其clone() 方法来返回那个子类 的实例。乍一看,您似乎正在使用Vertex 执行此操作,因为您返回的是Vertex。但是如果我这样做会怎样:

    export class SillyVertex extends Vertex {
      sillinessFactor: boolean = true;
      constructor()    
        super(0, 0, 0, new THREE.Vector3(), new THREE.Vector2());
      }
    }
    

    注意SillyVertexVertex 的子类,但它从Vertex 继承了clone() 方法。所以虽然(new SillyVertex()).clone()根据@​​987654338@的定义应该返回一个SillyVertex,但它将是一个Vertex。这是不正确的。


    如果您知道没有人会继承 Vertex 的子类,那么您总是可以保留 this 返回类型并在正文中进行类型断言:

    clone(): this {
      return new Vertex(this.x, this.y, this.z, this.normal.clone(), this.uv.clone()) as this;
    }
    

    no final keyword 将类标记为不可扩展,但添加私有构造函数或属性将具有相同的效果。


    如果您确实想要子类化Vertex,那么您将需要一个更通用的clone() 方法来处理所有可能的子类(通常很难做到,但可能类似于Object.assign() 可以帮助你)或小心在每个子类中正确实现clone()


    希望有所帮助;祝你好运!

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 2017-04-27
      • 2018-02-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2017-12-07
      • 2018-01-18
      相关资源
      最近更新 更多