TypeScript中的构造方法重载

TypeScript中的构造方法重载

本文介绍了TypeScript中的构造方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人在TypeScript中完成构造函数重载吗?在语言规范(v 0.8)的第64页上,有描述构造函数重载的语句,但是没有给出任何示例代码.

Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given.

我现在正在尝试一个非常基本的类声明;看起来像这样,

I'm trying out a really basic class declaration right now; it looks like this,

interface IBox {
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj: IBox) {
        this.x = obj.x;
        this.y = obj.y;
        this.height = obj.height;
        this.width = obj.width;
    }

    constructor() {
        this.x = 0;
        this.y = 0;
        this.width = 0;
        this.height = 0;
    }
}

与tsc BoxSample.ts一起运行时,它会抛出重复的构造函数定义-这是显而易见的.任何帮助表示赞赏.

When ran with tsc BoxSample.ts, it throws out a duplicate constructor definition -- which is obvious. Any help is appreciated.

推荐答案

TypeScript允许您声明重载,但只能有一个实现,并且该实现必须具有与所有重载兼容的签名.在您的示例中,可以轻松地通过使用可选参数来完成此操作,

TypeScript allows you to declare overloads but you can only have one implementation and that implementation must have a signature that is compatible with all overloads. In your example, this can easily be done with an optional parameter as in,

interface IBox {
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor(obj?: IBox) {
        this.x = obj && obj.x || 0
        this.y = obj && obj.y || 0
        this.height = obj && obj.height || 0
        this.width = obj && obj.width || 0;
    }
}

或两次重载,使用更通用的构造函数,如

or two overloads with a more general constructor as in,

interface IBox {
    x : number;
    y : number;
    height : number;
    width : number;
}

class Box {
    public x: number;
    public y: number;
    public height: number;
    public width: number;

    constructor();
    constructor(obj: IBox);
    constructor(obj?: any) {
        this.x = obj && obj.x || 0
        this.y = obj && obj.y || 0
        this.height = obj && obj.height || 0
        this.width = obj && obj.width || 0;
    }
}

这篇关于TypeScript中的构造方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:38