Call constructor on TypeScript class without new

后端 未结 6 945
醉话见心
醉话见心 2020-12-13 13:50

In JavaScript, I can define a constructor function which can be called with or without new:

function MyCl         


        
6条回答
  •  不思量自难忘°
    2020-12-13 14:22

    My workaround with a type and a function:

    class _Point {
        public readonly x: number;
        public readonly y: number;
    
        constructor(x: number, y: number) {
            this.x = x;
            this.y = y;
        }
    }
    export type Point = _Point;
    export function Point(x: number, y: number): Point {
        return new _Point(x, y);
    }
    

    or with an interface:

    export interface Point {
        readonly x: number;
        readonly y: number;
    }
    
    class _PointImpl implements Point {
        public readonly x: number;
        public readonly y: number;
    
        constructor(x: number, y: number) {
            this.x = x;
            this.y = y;
        }
    }
    
    export function Point(x: number, y: number): Point {
        return new _PointImpl(x, y);
    }
    
    

提交回复
热议问题