Languages
[Edit]
PL

TypeScript - przeciążenia konstruktora / wiele konstruktorów

3 points
Created by:
Sylwia
3500

W tym artykule przyjrzymy się, jak przeciążać konstruktor w języku TypeScript. W konstruktorze TypeScript przeładowanie wygląda inaczej niż w C ++, Javie czy C #. Głównym pomysłem na przeciążenie konstruktora jest utworzenie wspólnego konstruktora, który sprawdza jakiego rodzaju parametry były użyte, a później wykonuje logikę danego przypadku. Przydatne jest dodanie definicji konstruktorów, aby podpowiedzieć innym programistom, jak prawidłowo używać klasy.

 

Krótkie omówienie:

class MyClassName {

    public constructor(a : number);
    public constructor(a : number, b : number);
    public constructor(array : Array<number>);

    public constructor(...args : Array<any>) { // wspólny konstruktor

        // sprawdzenie argumentów i wykonanie odpowiedniego scenariusza
        // lub wyślij nowy błąd,że konstruktor nie jest obsługiwany('Constructor not supported!');
    }
}

// MyClassName  jest stosowany tutaj...

Poniżej praktyczny przykład:

1. Praktyczny przykład wielu konstruktorów

Przeciążenie konstruktora wymaga napisania logiki w celu wykrycia, który konstruktor został użyty. public constructor(...args : Array<any>) zawiera wspólną logikę, w której w zależności od użytych argumentów należy zastosować specjalny przypadek tworzenia obiektu.

class Point {
    private coordinates : Array<number>;

    public constructor(x : number, y : number);
    public constructor(x : number, y : number, z : number);
    public constructor(x : number, y : number, z : number, ...coordinates : Array<number>);
    public constructor(coordinates : Array<number>);

    public constructor(...args : Array<any>) { // wspólny konstruktor logiki
        if(args.length == 0)
            throw new Error('Arguments are not defined.');
    
        let arg = args[0];

        if(Array.isArray(arg)) {
            if(arg.length < 2)
                throw new Error('Minimum number of dimmensions is 2.');
        
            this.coordinates = arg;
        } else
            this.coordinates = args;
    }

    public getCoordinate(dimmension : number) : number {
        return this.coordinates[dimmension];
    }

    public toString() : string {
        let result = '{';

        if(this.coordinates.length > 0) {
            result += ' ' + this.coordinates[0];

            for(let i = 1; i < this.coordinates.length; ++i)
                result += ', ' + this.coordinates[i];
        }

        return result + ' }';
    }
}

let a = new Point(1, 2);
let b = new Point(1, 2, 3);
let c = new Point(1, 2, 3, 4);
let d = new Point([1, 2]);
let e = new Point([1, 2, 3]);
let f = new Point([1, 2, 3, 4]);

console.log(a.toString());
console.log(b.toString());
console.log(c.toString());
console.log(d.toString());
console.log(e.toString());
console.log(f.toString());

Wynik:

{ 1, 2 }
{ 1, 2, 3 }
{ 1, 2, 3, 4 }
{ 1, 2 }
{ 1, 2, 3 }
{ 1, 2, 3, 4 }

Bibliografia:

  1. Methods Overloading - Microsoft Docs
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join