发布于 2026-01-06 0 阅读
0

TypeScript 接口与类:附带实际示例 DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

TypeScript 接口与类:实例分析

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

TypeScript,我太爱它了。去Stack Overflow 做个调查,或者问问任何一个开发者,他们大多数都喜欢它。所有主流的 UI 库/框架(都效仿 Angular 的做法)现在都在添加 TypeScript 支持。虽然需要写一些额外的样板代码(使用JSON 转 TypeScript 的扩展),但类型检查、智能感知和即时视觉反馈带来的好处远远超过了这些额外的工作量。

我之前一直很困惑,接口和类都能完成工作,但是应该用哪一个,什么时候用呢?

TLDR

尽量使用接口,除非有接口无法满足的特殊需求,否则避免使用类。

.ts类在编译后会增加js文件的大小,.js而接口则不会。

班级需要额外排队

假设我们要给一个披萨对象赋予结构。我可以使用接口,也可以使用对象。

披萨界面

pizza-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);
Enter fullscreen mode Exit fullscreen mode

pizza-interface.js

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

Enter fullscreen mode Exit fullscreen mode

披萨课

pizza-class.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);
Enter fullscreen mode Exit fullscreen mode

pizza-class.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);
Enter fullscreen mode Exit fullscreen mode

线条越多.js,它的尺寸就越大。

课程用例

假设员工薪资包含住房补贴和公积金,这些都取决于基本工资。如果我想以最少的精力构建薪资对象结构,我可能会选择使用类而不是接口。

salary.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
    }
 */
Enter fullscreen mode Exit fullscreen mode

只需要两个输入,我就能创建一个对象。是不是很神奇?

这是我唯一能想到课堂教学更有效的场景。希望对您有所帮助。欢迎提出任何建设性的批评/反馈意见。

PS:我正在寻找Angular方面的新机会。如果您有任何职位空缺,请随时联系我。( krj2033@gmail.com ) ( linkedin )
文章来源:https://dev.to/raj_sekhar/typescript-interface-vs-class-5f6l