如何在对象内使用接口

Kousha

说我有这个:

interface Point {
    x: number;
    y: number;
}

interface Line {
    vertix1: Point;
    vertix2: Point;
}

let v1: Point = { x: 1, y: 2 };
let v2: Point = { x: 1, y: 2 };
let line: Line = {vertix1: v1, vertix2: v2};

如何line不定义v1直接定义v2我尝试了,但是显然没有用:

let line1: Line = {
    vertix1: Point = { x: 1, y: 2 },
    vertix2: Point = { x: 1, y: 2 },
}
Moustache_Me_A_Question

使用实现接口的类可能会更好。

interface IPoint {
    x: number;
    y: number;
}

interface ILine {
    vertix1: Point;
    vertix2: Point;
}

class Point implements IPoint {
  x: int;
  y: int;

  constructor(x: int, y: int) {
    this.x = x;
    this.y = y;
  }
}

class Line implments ILine {
  vertix1: Point;
  vertix2: Point;

  constructor(vertix1: Point, vertix2: Point) {
    this.vertix1 = vertix1;
    this.vertix2 = vertix2;
  }
}
let v1: Point = new Point(1,2);
let v2: Point = new Point(1,2);
let line: Line = new Line(v1,v2);

您也可以在构造函数中创建点。不知道这是否能回答您的问题,但希望能对您有所帮助。

let line: Line = new Line(new Point(1,2), new Point(1,2))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章