Typescript インターフェイスとクラスの実際の例


タイプスクリプト、大好きです. stackoverflow survey を取るか、開発者に尋ねると、ほとんどの開発者がそうします.すべての主要な UI ライブラリ/フレームワークは (Angular の方法に従って) Typescript のサポートを追加しています.少し余分なボイラープレートを作成する必要がありますが (json to ts 拡張を使用)、型チェック、インテリセンス、および即時の視覚的フィードバックの利点が余分な作業を上回ります.

インターフェイスとクラスの両方が作業を完了する場所でこの混乱がありましたが、どちらをいつ使用するのでしょうか?

TLDR



インターフェースで実行できない特別な要件がない限り、インターフェースを使用し、クラスを避けます.

Classes add to js file size, after compiling .ts to .js, while interfaces do not



クラスには余分な行が必要です



ピザオブジェクトに構造を与えたいシナリオを考えてみましょう.インターフェイスまたはオブジェクトを使用できます.

ピザインターフェース



ピザ-interface.ts

interface Pizza {
    variant: string;
    size: string,
    price: number;
    extraCheese: boolean;
    takeAway: boolean;
}

const myPizza: Pizza = {
    variant: 'Maxican green wave', size: 'medium', price: 550, extraCheese: true, takeAway: false,
}
console.log(myPizza);


ピザ-interface.js

var myPizza = {
    variant: 'Maxican green wave', size: 'medium', price: 550, extraCheese: true, takeAway: false
};
console.log(myPizza);



ピザ教室



ピザクラス.ts

class Pizza {
    variant: string;
    size: string;
    price: number;
    extraCheese: boolean;
    takeAway: boolean;

    constructor(variant: string, size: string, price: number, extraCheese: boolean, takeAway: boolean) {
        this.variant = variant;
        this.size = size;
        this.price = price;
        this.extraCheese = extraCheese;
        this.takeAway = takeAway;
    }
}

const myPizza = new Pizza('Maxican green wave', 'medium', 550, true, false);
console.log(myPizza);


ピザクラス.js

var Pizza = /** @class */ (function () {
    function Pizza(variant, size, price, extraCheese, takeAway) {
        this.variant = variant;
        this.size = size;
        this.price = price;
        this.extraCheese = extraCheese;
        this.takeAway = takeAway;
    }
    return Pizza;
}());
var myPizza = new Pizza('Maxican green wave', 'medium', 550, true, false);
console.log(myPizza);


More the lines in your .js, more is its size



クラスのユースケース



従業員の給与のシナリオを考えてみましょう.ここで、HRA、PF の貢献は基本額に依存します.したがって、給与オブジェクトの構造を最小限の労力で提供したい場合は、ここではインターフェイスの代わりにクラスを使用することがあります.

給料.ts

class SalaryComponents {
    basic: number;
    pf: number;
    hra: number;
    professionalTax: number;

    constructor(basic: number, state: string) {
        this.basic = basic;
        this.hra = basic * 0.5;
        this.pf = basic * 0.12;
        this.professionalTax = this.getProfessionalTax(state);
    }

    getProfessionalTax(stateName: string): number {
        return 2000; // dummy value
    }
}

const emp1 = new SalaryComponents(1000, 'Tamil Nadu');
console.log(emp1); 
/** Output
    {
        basic: 1000,
        hra: 500,
        pf: 120,
        professionalTax: 2000
    }
 */


2 つの入力だけで、オブジェクトを作成できました.かなりきれいですね!!

これは、クラスがより効果的であると考えられる唯一のシナリオです.お役に立てば幸いです.建設的な批判やフィードバックを歓迎します.


PS: Angular での新しい機会を探しています.空きがあれば、メッセージでお知らせします. ( [email protected] ) ( )