What is the difference between type and class in Typescript?

前端 未结 4 591
旧巷少年郎
旧巷少年郎 2020-11-29 10:30

What is the difference between type and class?

type Point {
  x: number, y: number
}

let p = new Point();

The ab

4条回答
  •  独厮守ぢ
    2020-11-29 10:53

    You use a type (or in other cases an interface) for type annotations to indicate the structure of JavaScript objects:

    type Point = {
      x: number, y: number
    }
    
    function doSomething(p: Point) {
    }
    
    let p: Point = { x: 10, y: 15 };
    doSomething(p);
    

    These type annotations are subject to structural typing, meaning that in this specific case you could drop the type annotation:

    let p = { x: number, y: number };
    doSomething(p);
    

    A class is something entirely different, which provides you a more elegant alternative to JS prototype inheritance:

    class Point {
        public x: number;
        public y: number;
    
        constructor(x: number, y: number) {
            this.x = x;
            this.y = y;
        }
    
        public move(deltaX: number, deltaY: number) {
            this.x = this.x + deltaX;
            this.y = this.y + deltaY;
        }
    }
    
    let p = new Point(10, 15);
    p.move(1, 2);
    

    When you look at the generated JS code, you will quickly notice the difference:

    The type declaration is dropped in the generated code.

    The class definition is turned into a JS function with prototype inheritance

提交回复
热议问题